Java OCA OCP Practice Question 706


Which of the answer choices results in a different value being output than the other three choices?

StringBuilder sb = new StringBuilder("A "); 
sb = ____; 
A.  new StringBuilder("A ") 

B.  new StringBuilder("A ") 
         .delete(1, 100) /*w ww. j a  va2s .  c om*/
         .insert(1,  "adical r") 

C.  new StringBuilder("A ") 
         .insert(7, "robots") 

D.  new StringBuilder("A ") 
         .insert(sb.length(), "robots") 



Option A is straightforward and outputs A robots.

Option B does the same in a convoluted manner.

First Option B removes all the characters after the first one.

It doesn't matter that there aren't actually 100 characters to delete.

Then it appends obots to the end, making the builder contain robots.

It inserts the remainder of the string immediately after the first index.

Option D creates the same value by inserting robots immediately after the end of the StringBuilder.

Option C is close, but it has an off-by-one error.

It inserts robots after the letter l rather than after the space.