• Post Reply Bookmark Topic Watch Topic
  • New Topic

== operator not return true  RSS feed

 
G.Sathish kumar
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when


above code have to return true but return false when the string created using new operation but String s = "ranch" and String s1="ranch" the == return true

can any body please explain what is the internal
 
John Bengler
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

if you use == for comparing two Strings (or other objects) you compare if it is the same object, not if the content is the same. you should usethe equals() method.

See this for details:

how to compare string objects


As I said before: this is applicable to all objects.


John
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Java Linux
 
Vinod Tiwari
Ranch Hand
Posts: 466
1
IntelliJ IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this http://leepoint.net/notes-java/data/expressions/22compareobjects.html

Let me know if you have some issues.

Thanks
Vinod
 
Manish Ramrakhiani
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you use ==, it actually checks if both the operands are pointing to the same object, if yes, it returns true.
When you use equals, it actually compares the content, and if same, it returns true.

Now when you use
String s = new String("ranch");
String s1 = new String("ranch") ;

Two string objects are getting created which are being refrenced by two different References that is s and s1.

Howevr, when you use
String s = "ranch"
String s1 ="ranch"

JVM internally creates only one object (Interned object).
So since there is only one object in this case and both the refrences are pointing to the same object, == is also returning true.

Hope you understood..
Please write back in case of any issues...

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!