Rachel
Rachel

Reputation: 103447

Which is correct usage of equals method in java?

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

Answers (2)

Attila
Attila

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

Edwin Buck
Edwin Buck

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

Related Questions