Java String Literal Comparison and NullPointerException

When comparing String literals to String variables I often come across the following style of code:

final String MY_NAME = "Steve";

void myMethod(String aName) {
  if (aName.equals(MY_NAME)) {
    	// do something
    }
}

If I were to call the above method with a null argument, it would throw a NullPointerException. Of course you could add a defensive check but you would also be adding complexity and increasing method/codebase size:

final String MY_NAME = "Steve";

void myMethod(String aName) {
  // defensive check to avoid NullPointerException
  if (aName == null) {
    	return;
  }
  if (aName.equals(MY_NAME)) {
    	// do something
    }
}

A better solution to defending against a NullPointerException in such a scenario is to simply place the literal first. the String.equals methods will happily handle a null argument and you know your String literal will never be null (unless you explicitly set it of course):

final String MY_NAME = "Steve";

void myMethod(String aName) {
  if (MY_NAME.equals(aName)) {
    	// do something
    }
}
Codementor Tutorials责编内容来自:Codementor Tutorials (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Java String Literal Comparison and NullPointerException

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录