Originally posted by Nayyer Kamran:
hi every one,
I am facing problem while understanding the string equlity. the following chunk of code returns
output:
false
true
Source:
public class StringEqual{
public static void main(String args[]){
String a= new String("Hello");
String b ="Hello";
System.out.println(a.toString()=="Hello");
System.out.println(b.toString()=="Hello");
}
}
Why so I want to know the logic behind what a.toString() returns to compare that result in "false" and what b.toString() returns to compare that result in "true".
thx in advance
Nayyer
Nayyar,
In
java Strings are objects and they are mantained in a pool.
Whenever we create a string object like
<PRE>
String s = "Hello";
</PRE>
the obj. ref. s is pointing to the object which is in the pool(if it is created already). But if we something like
<PRE>
String s = new String("Hello");
</PRE>
Then s refers to an object which is NOT the same object which is there in the pool.
Now come to your case.
you did
String a = new String("Hello");
and called
a.toString() which returns a new String Object.
again, Java creates one more string object when you do "Hello".
But this object refers to the pool.
When you create the second object like
String b = "Hello";
java sees that the object "Hello" is already there in the pool so it assignes the that reference to b.
So the first comparison results in false since a is pointing to object different than the object returned by a.toString() (which is the object in pool).
The second time the comparison results to true since the object b refers to the same object in the pool which is returned by b.toString().
I think this will clear your doubt.
-vadiraj