Avoiding NullPointerException when Comparing string values
Compare strings/constants by putting them on the left side of the comparison
You can avoid many NullPointerExceptions by simply always placing hardcoded string and constants on the left side of an object comparison. This works well for any object constants (not just strings).
For example, this code can generate a NullPointerException if myString is null (bad):
if(myString.equals("hardcodedstring" )) {
// dosomething
}
This example code can never generate a NullPointerException (good):
if("hardcodedstring".equals(myString)) {
// dosomething
}
Tuan Izzath Abdeen
Senior Solutions Developer
You can avoid many NullPointerExceptions by simply always placing hardcoded string and constants on the left side of an object comparison. This works well for any object constants (not just strings).
For example, this code can generate a NullPointerException if myString is null (bad):
if(myString.equals("
// dosomething
}
This example code can never generate a NullPointerException (good):
if("hardcodedstring".equals(
}
Tuan Izzath Abdeen
Senior Solutions Developer
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home