Multiple choice

Which of the following options provides the output of this program, when executed? class Sample4 { public static void main(String []args) { String s1 =" Hello Java"; String s2 = new String("Hello Java"); String s3 =" Hello Java"; if(s1 == s2) { System.out.println("s1 and s2 equal"); } else { System.out.println("s1 and s2 not equal"); } if(s1 == s3) { System.out.println("s1 and s3 equal"); } else { System.out.println("s1 and s3 not equal"); } } }

  1. s1 and s2 equal s1 and s3 equal

  2. s1 and s2 equal s1 and s3 not equal

  3. s1 and s2 not equal s1 and s3 not equal

  4. s1 and s2 not equal s1 and s3 equal

  5. None of the above

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

JVM sets a constant pool in which it stores all the string constants used in the type. If two references are declared with a constant, then both refer to the same constant object. The == operator checks the similarity of the objects itself (and not the values in it). Here, the first comparison is between two distinct objects, so we get s1and s2 not equal. On the other hand, since references of s1 and s3 refer to the same object, we get s1 and s3 equal.