OCA Java SE 8 Method - OCA Mock Question Method 21








Question

Which of the following are output by the following code?

public class Main {
  public static StringBuilder work(StringBuilder a, StringBuilder b) {
    a = new StringBuilder("BBB");
    b.append("AAA");
    return a;
  }

  public static void main(String[] args) {
    StringBuilder s1 = new StringBuilder("StringBuilder1");
    StringBuilder s2 = new StringBuilder("StringBuilder2");
    StringBuilder s3 = work(s1, s2);
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
  }
}
  1. s1 = BBB
  2. s1 = StringBuilder1
  3. s2 = StringBuilder2
  4. s2 = StringBuilder2AAA
  5. s3 = BBB
  6. s3 = null
  7. The code does not compile.




Answer



B, D, E.

Note

Java is pass-by-reference.

Calling append() affects the caller if both the method parameter and caller have a reference to the same object.

Returning a value passes the reference to the caller for assignment.

public class Main {
  public static StringBuilder work(StringBuilder a, StringBuilder b) {
    a = new StringBuilder("BBB");
    b.append("AAA");
    return a;
  }

  public static void main(String[] args) {
    StringBuilder s1 = new StringBuilder("StringBuilder1");
    StringBuilder s2 = new StringBuilder("StringBuilder2");
    StringBuilder s3 = work(s1, s2);
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
  }
}