• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is there a difference in how equals() is used?  RSS feed

 
Elle Atechsy
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have noticed that some developers use the equals() method 2 different ways. Please see examples of both below.

strgVariable.equals("strValue")

"strValue".equals(strgVariable)


Is there a difference between the 2 techniques or just the developer's preference?

Thanks,
Lulu
 
Vinny Menon
Ranch Hand
Posts: 62
Java Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
When you mention the first case :strgVariable.equals("strValue"),in this case,there is a possibility of
NullPointerException
in case strgVariable is null.

However,when you mention the second case:"strValue".equals(strgVariable),in this case,a constant value will be compared to the variable(even if it is null, the comparison will return false.)
And no null check is required for the second case.
Hope this is clear.
thanks
vinnym
 
Elle Atechsy
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm, that makes sense, thank you for your quick response.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!