Wednesday 27 February 2013

23. Which of the following lines will print false?

23. Which of the following lines will print false?

Choices:
a. Lines 10 and 12
b. Line 12 only
c. Line 8 and 10
d. None of these

Answer:-

D is correct.
Only line 10 will print false.
Strings are immutable objects.
That is, a string is read only once the string has been created and initialized, and Java optimizes handling of string literals; only one anonymous string object is shared by all string literals with the same contents.
Hence in the above code the strings s1, s2 and s4 refer to the same anonymous string object, initialized with the character string: "I am unique!".
Thus s1 == s2 and TestClass.s4 will both return true and obviously s1.equals(s2) will return true.
But creating string objects using the constructor String(String s) creates a new string, hence s3 == s1 will return false even though s3.equals(s1) will return true because s1 and s3 are referring to two different string objects whose contents are same.

No comments:

Post a Comment