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








Question

What is the output of the following code?

public class Main { 
    public static void main(String args[]) { 
            StringBuilder s = new StringBuilder(10 + 2 + "ABC" + 4 + 5); 
            s.append(s.delete(3, 6)); 
            System.out.println(s); 
    } 
} 
  1. 12A512A5
  2. 12A12A
  3. 1025102A
  4. Runtime exception




Answer



A

Note

The following line of code returns 12ABC45:

10 + 2 + "ABC" + 4 + 5 

The + operator adds two numbers but concatenates the last two numbers.

When the + operator encounters a String object, it treats all the remaining operands as String objects.

s.delete(3, 6) modifies the existing value of the StringBuilder to 12A5.

It then appends the same value to itself when calling s.append(), resulting in the value 12A512A5.