Java OCA OCP Practice Question 2026

Question

What will the following program print when run?.

public class Main {
  public static void main (String[] args) {
    String s1 = "WOW";
    StringBuilder s2 = new StringBuilder(s1);
    String s3 = new String(s2);
    System.out.println((s1.hashCode() == s2.hashCode()) + " " +
                        (s1.hashCode() == s3.hashCode()));
  }
}

Select the one correct answer.

  • (a) The program will print false true.
  • (b) The program will print false false.
  • (c) The program will print true false.
  • (d) The program will print true true.
  • (e) The program will fail to compile.
  • (f) The program will compile, but throw an exception at runtime.


(a)

Note

The StringBuilder class does not override the hashCode() method, but the String class does.

The references s1 and s2 refer to a String object and a StringBuilder object, respectively.

The hash values of these objects are computed by the hashCode() method in the String and the Object class, respectively-giving different results.

The references s1 and s3 refer to two different String objects that are equal, hence they have the same hash value.




PreviousNext

Related