Str.equals ("String") vs "String" .equals (str)

Is there a performance impact if stris java.lang.Stringusing "String".equals(str)vs str.equals("String")? My gut says, “No, the JVM / compiler optimizes the literal string anyway,” but I see that the first style is trimmed enough in different codebases and it looks so unnatural (at least for me), so I decided that there should be a reason besides style.

+4
source share
2 answers

The only reason for using "String".equals(str)(which I find ugly) is laziness, as it saves you from having to check that str != nullbefore the call str.equals("String").

Efficiency should not be any difference. You are comparing two instances Stringanyway.

+7
source
"String".equals(str)

Does not give the same result as

str.equals("String")

if str == null.

In the first case, it returns false, and in the second - a NullPointerException.

"String".equals(str)

Actually equivalent

str != null && str.equals("String")
0
source

All Articles