Is there a performance impact, assuming str is a java.lang.String, of using "String".equals(str) vs str.equals("String")? My gut says, "No, the JVM / compiler will optimize the literal string in either case", but I see the first style crop up enough in various codebases and it just looks so unnatural (at least to me), so I figured there must be a reason besides style.
            Asked
            
        
        
            Active
            
        
            Viewed 313 times
        
    4
            
            
        2 Answers
7
            The only reason for using "String".equals(str) (which I find ugly) is laziness, as it saves you the need to check that str != null prior to calling str.equals("String").
Performance-wise there shouldn't be any difference. You are comparing two String instances either way.
 
    
    
        Eran
        
- 387,369
- 54
- 702
- 768
0
            
            
        "String".equals(str)
Does not yield the same result as
str.equals("String")
if str == null.
In the first case, it returns false, in the second, it throws a NullPointerException.
"String".equals(str)
Is in fact equivalent to
str != null && str.equals("String")
 
    
    
        njzk2
        
- 38,969
- 7
- 69
- 107
