Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String query

 
pankaj kapoor
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s = new String("abc");
String b = new String("abc");
if(s==b )
System.out.println("equal");

String s1 = "abc";
String b1 = "abc";
if(s1==b1 )
System.out.println("equal String");

In the above code s1==b1 prints "equal String"
while s==b does not print "equal"

could anyone explain to me the reason for this .
Thanks in advance
 
Craig Tyler
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== tests if the objects being compared are actually the same object. In your example, s and b are different objects with the same contents, so while they pass the equals() test because they have the same contents, they produce false when using ==.

s1 and b1 both refer to the same object in the string literal pool, so they pass both == and equals().
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"new" will create to new objects, that is why "==" returns false.

However, using "=" will get an existing object from the pool, or create a new one if it does not exist. There is already a String whose value is "abc", so it will return the same reference to that String. Same reference, means that "==" will return true.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic