OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 4-5








Question

Which of the following can replace line 2 to print "DCBA"? (Choose all that apply)

     1: StringBuilder v = new StringBuilder("ABCD"); 
     2: // INSERT CODE HERE 
     3: System.out.println(v); 
  1. v.reverse();
  2. v.append("CBA$").substring(0, 4);
  3. v.append("CBA$").delete(0, 3).deleteCharAt(v.length() - 1);
  4. v.append("CBA$").delete(0, 3).deleteCharAt(v.length());
  5. None of the above.




Answer



A, C.

Note

The reverse() method can do the trick.

Option C creates the value "ABCDCBA$". Then it removes the first three characters, resulting in "DCBA$". Finally, it removes the last character, resulting in "DCBA".

public class Main{
   public static void main(String[] argv){
      StringBuilder v = new StringBuilder("ABCD"); 
      v.reverse();  
      System.out.println(v); 
   
   }
}




Example

public class Main{
   public static void main(String[] argv){
      StringBuilder v = new StringBuilder("ABCD"); 
      v.append("CBA$").delete(0, 3).deleteCharAt(v.length() - 1); 
      System.out.println(v); 
   
   }
}

The code above generates the following result.