Tuesday 20 December 2011

What will be the result of compiling and running the following code fragment?

Integer i= new Integer("10");

if (i.toString() == i.toString())

System.out.println("Equal");


else

System.out.println("Not Equal");


Choices:

A. Compiler error
B. Prints "Equal"
C. Prints "Not Equal"
D. None of the above


Correct choice:

  • C


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, the else statement is executed, and "Not Equal" is printed out.

No comments:

Post a Comment