I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.
Recomendation:
String variable;
"xx".equals(variable) // OK
variable.equals("xx") //Not recomended
Because prevents appearance of NullPointerException that are not controlled
Is this true?
Specifically with regard to strings, yes, == is slightly faster than equals , because the first thing the String.
Definition and Usage The equals() method compares two strings, and returns true if the strings are equal, and false if not.
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).
The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. The String equals() method overrides the equals() method of the Object class.
This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException
. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.
But:
NullPointerException
is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.
It is true. If variable
is null
in your example,
variable.equals("xx");
will throw a NPE because you can't call a method (equals
) on a null object. But
"xx".equals(variable);
will just return false
without error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With