OCA Java SE 8 Mock Exam 2 - OCA Mock Question 21








Question

What is the output of the following code?

public class Main {
  public static void main(String args[]) {
    String s1 = new String("Java");
    String s2 = new String("Java");
    String s3 = "Java";
    String s4 = "Java";
    do
      System.out.println(s1.equals(s2));
    while (s3 == s4);
  }
}
  1. true printed once
  2. false printed once
  3. true printed in an infinite loop
  4. false printed in an infinite loop




Answer



C

Note

String objects that are created without using the new operator are placed in a pool of Strings.

s3 and s4 are in a pool of Strings and are pointing the same string object.

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) 

The variables s1 and s2 refer to different String objects, they have 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.