Wednesday, May 31, 2006

comparinng Integer objects as String

Integer i= new Integer("10");
if (i.toString() == i.toString())
System.out.println("Equal");
else
System.out.println("Not Equal");


The output is "Not Equal". Certainly Strange. See the explanation.

The toString() method returns the String equivalent of this String object. It creates a new object each time it is called. The == operator compares the bit patterns of the two object references and not the actual String contents. Thus the comparison returns false, theelse statement is executed, and "Not Equal" is printed out.

0 Comments:

Post a Comment

<< Home