Java OCA OCP Practice Question 903

Question

Which of the following can replace line 4 to print avaJ?

Choose all that apply

3: StringBuilder puzzle = new StringBuilder("Java"); 
4: // INSERT CODE HERE 
5: System.out.println(puzzle); 
A. puzzle.reverse(); 
B. puzzle.append("vaJ$").substring(0, 4); 
C. puzzle.append("vaJ$").delete(0, 3).deleteCharAt(puzzle.length() - 1); 
D. puzzle.append("vaJ$").delete(0, 3).deleteCharAt(puzzle.length()); 
E. None of the above. 


A, C.

Note

The reverse() method is the easiest way of reversing the characters in a StringBuilder;

Option A is correct.

Option B is a nice distraction-it does in fact return avaJ.

substring() returns a String, which is not stored anywhere.

Option C uses method chaining.

Option D throws an exception because you cannot delete the character after the last index.

deleteCharAt() uses indexes that are zero based and length() counts starting with 1.




PreviousNext

Related