I have seen most cases developers use first string and after that variable used in .equal
operation. What is the reason?
why in Java, (“string”).equals(var) recommended other than (var).equals(“string”)?
This is because you do not know for sure what is var pointing to. It may very well be null because of which you may get NPE which will kill your current Thread. So 2nd approach is preferred as (“string”).equals(var)
returns false.
For example consider you getting this var in your servlet
String var = request.getParameter("myvar");
if(var.equals("myVarValue")) {
//do something
}
This will throw NPE if parameter is not coming in your request.
I would not use ("string").equals(var), since it may show that the programmer does not know if var might be null or not. I would document if a var can be null or not and check it.
Example:
String makeAString(@NonNull String aStringValue) {
Validate.notNull(aStringValue, "aStringValue must not be null");
if (aStringValue.equals("abcde") {
return "fg";
} else {
return "de";
}
}
String makeAString(@Nullable String aStringValue) {
if (aStringValue == null) {
return "kl";
}
if (aStringValue.equals("abcde") {
return "fg";
} else {
return "de";
}
}
Because if var is null you won't raise a NullPointerException.
public static void badOne() {
String s = null;
System.out.println(s.equals("abc"));
// This function will throw null pointer
}
public static void goodOne() {
String s = null;
System.out.println("abc".equals(s));
// This will print false
}
Because var can be null
and var.equals("string") will throw NullPointerException (attempt to call of method on null). On the other hand, "string".equals(null)
will just return false.