• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
ShaikSalam Bashoeb
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the first will return 'false' if str is null in the first case, it will throw a NullPointerException in the second
 
ShaikSalam Bashoeb
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Millions of Thanks David
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic