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








Question

What is the output of the following code?

public class Main {
  public static void main(String args[]) {
    StringBuilder sb1 = new StringBuilder("123456");
    sb1.subSequence(2, 4);
    sb1.deleteCharAt(3);
    sb1.reverse();
    System.out.println(sb1);
  }
}
  1. 521
  2. Runtime exception
  3. 65321
  4. 65431




Answer



C

Note

sb1 remains 123456 after the execution of the following line of code:

sb1.subSequence(2, 4); 

Since subSequence returns the sub sequence and keeps the sb1 unchanged.

The method deleteCharAt deletes a char value at position 3.

Because the positions are zero-based, the digit 4 is deleted from the value 123456, resulting in 12356.

The method reverse modifies the value of a StringBuilder by assigning to it the reverse representation of its value.

The reverse of 12356 is 65321.

public class Main {
  public static void main(String args[]) {
    StringBuilder sb1 = new StringBuilder("123456");
    sb1.subSequence(2, 4);
    sb1.deleteCharAt(3);
    sb1.reverse();
    System.out.println(sb1);
  }
}

The code above generates the following result.