File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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: 19653
    
  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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: difference between "john".equals(str) and str.equals("john")
 
Similar Threads
hashCode Question
Incorrect equals() implementation...
Please explain the output
String intern();
JButton not working