This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes difference between Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "difference between "john".equals(str) and str.equals("john")" Watch "difference between "john".equals(str) and str.equals("john")" New topic
Author

difference between "john".equals(str) and str.equals("john")

ShaikSalam Bashoeb
Greenhorn

Joined: Dec 10, 2008
Posts: 24
HI. May i know the difference between
and

What I heard is Better approach is the First Code.

Any Suggestions will be appreciated................
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

the first will return 'false' if str is null in the first case, it will throw a NullPointerException in the second
ShaikSalam Bashoeb
Greenhorn

Joined: Dec 10, 2008
Posts: 24
Millions of Thanks David
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20080
    
  30


is more or less similar to

And that extra part of the condition is exactly why several programmers, me included, prefer calling equals on the String constant, not the variable.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

and in practice it is better to call .equals() on the known part and not jsu for Strings. Keep this in mind for Integers and other types.
 
Have you checked out Aspose?
 
subject: difference between "john".equals(str) and str.equals("john")
 
It's not a secret anymore!