Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling equals method on String

 
shashi kir
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a String s="apple"
What is the difference between s.equals("apple") and "apple".equals(s)? and which is better? Please post the correct answer
 
Campbell Ritchie
Sheriff
Pie
Posts: 49770
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That depends which language you are using. Both are valid syntax in Java, but they mean different things. I think only the one with = is valid SQL syntax, but you should check whether you want "apple" or 'apple' in SQL.

If you try passing s in Java and s is null, then s.equals... will throw a NullPointerException and "apple".equals(s) will evaluate to the value false.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic