OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 1-1








Question

What is the result of the following code?

public class Main{
   public static void main(String[] argv){
       StringBuilder sb = new StringBuilder(); 
       sb.append("AAA").insert(1, "BB").insert(4, "CCCC"); 
       System.out.println(sb); 
   }
}
  1. ABBAACCCC
  2. ABBACCCCA
  3. BBAAACCCC
  4. BBAACCCCA
  5. An exception is thrown.
  6. The code does not compile.




Answer



B.

Note

The code uses method chaining.

After the call to append(), sb contains "AAA".

That result is passed to the first insert() call, which inserts at index 1. At this point sb contains ABBbAA.

That result is passed to the final insert(), which inserts at index 4, resulting in ABBACCCCA.

public class Main{
   public static void main(String[] argv){
       StringBuilder sb = new StringBuilder(); 
       sb.append("AAA").insert(1, "BB").insert(4, "CCCC"); 
       System.out.println(sb); 
   }
}