What is the result of the following code?
StringBuilder sb = new StringBuilder("A") .insert(sb.length(), "robots"); System.out.println(sb);
A. arobots
B. Arobots
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
C.
Calling the constructor and then insert()
is an example of method chaining.
Rhe sb.length()
call is a problem.
The sb reference doesn't exist until after the chained calls complete.
Just because it happens to be on a separate line doesn't change when the reference is created.
Since the code does not compile, Option C is correct.