Reputation: 103447
Simple question, which is correct way of using equals
, also provide reasoning behind answer.
"Delta".equals(type)
or
type.equals("Delta")
Upvotes: 2
Views: 128
Reputation: 28762
Both are correct. The first calls the compare method on a definitely non-null string, so it will not throw a NullPointerException, the second might if type
is null
The sfirst version is "safer", the second "reads" more naturally
Upvotes: 1
Reputation: 70909
Generally
"Delta".equals(type)
is favored, as it is impossible to throw a NullPointerException
. That said, the other way is not "incorrect" as it is not in error with the Java Language Specification; however, it is just susceptible to failure if (type == null)
is true.
The term "best practice" is used to differentiate a better choice from a correct, but inferior choice. In this case "Delta".equals(type)
is a best practice, to avoid the unnecessary guard code required to handle null pointer references.
Upvotes: 8