OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 2-7








Question

What is the result of the following code?

public class Main {
  public void AAA(String v1, StringBuilder v2) {
    v1.concat(".");
    v2.append(".");
  }

  public static void main(String[] args) {
    String v1 = "AAA";
    StringBuilder v2 = new StringBuilder("AAA");
    new Main().AAA(v1, v2);
    System.out.println(v1 + " " + v2);
  }
}
  1. AAA AAA
  2. AAA AAA.
  3. AAA. AAA
  4. AAA. AAA.
  5. An exception is thrown.
  6. The code does not compile.




Answer



B.

Note

A String is immutable.

Calling stringReference.concat() returns a new String but does not change the stringReference.

A StringBuilder is mutable. Calling stringBuilderReference.append() adds characters to the existing character sequence and returns a reference to the same object.