This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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 Murach's Java Servlets and JSP this week in the Servlets 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: 19649
    
  18


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
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.
 
wood burning stoves
 
subject: difference between "john".equals(str) and str.equals("john")
 
Similar Threads
Incorrect equals() implementation...
Please explain the output
String intern();
JButton not working
hashCode Question