What will be the output of the following code?
public class StringTest { public static void main(String [] a) { String s1 = "test string"; String s2 = "test string"; if (s1 == s2) { System.out.println("same"); } else { System.out.println("different"); } //from w w w . j a v a 2 s .co m } }
D.
Both String variables are assigned the same string, "test string".
Because these strings are not created using the new String()
method.
The strings are placed in the string pool, and a reference to those strings is stored in the String variables.
Because the reference to the string pool is the same, the == comparison will return true.
If the strings were created using the new String()
method, the references would be different and the == comparison would return false.