Why myString.equals ("aString"); different from "aString" .equals (myString) ;?

I heard several times that when using boolean equals(Object o) to compare Strings it is better to put a constant on the left side of the function, as shown below:

  • Bad: myString.equals ("aString");
  • Good: "aString" .equals (myString);

Why is this?

+7
source share
3 answers

Because if myString is null, you get an exception. You know that "aString" will never be empty, so you can avoid this problem.

Often you will see libraries that use nullSafeEquals(myString,"aString"); everywhere to avoid this (since most often you compare objects, they are not generated by the compiler!)

+8
source

This is a protective technique to protect against NullPointerException s. If your constant is always on the left, you do not have NPE when calling equals .

+3
source

This is a bad design because you are hiding NullPointerExceptions. Instead of being warned that the string is NULL, instead you will get some strange behavior in the program, and the exception is in another place.

But it all depends on whether "null" is valid for your string. Normally, "null" should never be considered the reasonable state of an object to pass through.

+1
source

All Articles