What is the output of the following code?
public class Main { public static void main(String args[]) { String s1 = new String("abc"); String s2 = new String("abc"); String s3 = "abc"; String s4 = "abc"; do //from w w w.j av a 2 s . com System.out.println(s1.equals(s2)); while (s3 == s4); } }
c
String objects that are created without using the new operator are placed in a pool of Strings.
Hence, the String object referred to by the variable s3 is placed in a pool of Strings.
The variable s4 is also defined without using the new operator.
Before Java creates another String object in the String pool for the variable s4, it looks for a String object with the same value in the pool.
Because this value already exists in the pool, it makes the variable s4 refer to the same String object.
This, in turn, makes the variables s3 and s4 refer to the same String objects.
Hence, both of the following comparisons will return true:.
s3 == s4 (compare the object references) s3.equals(s4) (compare the object values)
Even though the variables s1 and s2 refer to different String objects, they define the same values.
So s1.equals(s2) also returns true.
Because the loop condition (s3==s4) always returns true, the code prints true in an infinite loop.