I just was tidying my code a bit and there was this piece:
String saving = getValue();
if(saving != null && saving.equals(\"true\")){
// do someth
The format of putting the literal first avoids the potential NPE and will always be false for "literal".equals(null)
.
This is because a "literal" expression always evaluates to a String object (and is thus never null) and String.equals(obj)
checks to see if the other object is a null (via asinstanceof
). An object is an object - no need to worry bout the "heap".
It's good practice to have a null-guard in an equals implementation as null.equals(null)
is not permissible: "The equals method implements an equivalence relation on non-null object references"
Here is the String.equals the source (for OpenJDK):
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
// ..
}
return false;
}
This is safe - and as you have seen, a good way of avoiding null pointers.
You mention the use of new
for Strings. Many java static code analysis tools will recommend always using literals over new String("foo");
.
Edit:
If you wanted, you could even just use:
if (Boolean.valueOf(saving)) {
...
}
According to the docs, passing null
will return false
.