wood burning stoves
The moose likes Beginning Java and the fly likes String query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String query" Watch "String query" New topic

String query

pankaj kapoor

Joined: Sep 22, 2005
Posts: 17
String s = new String("abc");
String b = new String("abc");
if(s==b )

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

Joined: Jan 15, 2006
Posts: 52
== 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é

Joined: Nov 24, 2005
Posts: 14688

"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.

[My Blog]
All roads lead to JavaRanch
I agree. Here's the link: http://aspose.com/file-tools
subject: String query
It's not a secret anymore!