Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I heard several times that in using boolean equals(Object o) to compare Strings, it's better to put the constant on the left side of the function as in the following:

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

Why is this?

like image 837
Marsellus Wallace Avatar asked Sep 28 '11 00:09

Marsellus Wallace


2 Answers

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

Often you'll see libraries that use nullSafeEquals(myString,"aString"); everywhere to avoid exactly that (since most times you compare objects, they aren't generated by the compiler!)

like image 155
corsiKa Avatar answered Oct 14 '22 07:10

corsiKa


This is a defensive technique to protect against NullPointerExceptions. If your constant is always on the left, no chance you will get a NPE on that equals call.

like image 25
markdsievers Avatar answered Oct 14 '22 06:10

markdsievers