简体   繁体   中英

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")

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM