Oracle Certified Associate Java Se 8 Programmer · Free Practice Question Medium
Question 45
What will be the result of compiling and executing StringBuilderTest class?
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Morning"); // Line 3
modify(sb); // Line 4
System.out.println(sb); // Line 5
}
private static void modify(StringBuilder s) {
s.append("_Sun"); // Line 9
}
}
-
A
Good_Sun
-
B
_Sun
-
C
None of the other options
-
D
Morning_Sun
Reveal correct answer
Correct answer: D
Explanation
When the modify method is called, both the s and sb variables refer to the same StringBuilder object. Line 9 modifies the object by appending "_Sun" to it. As a result, s refers to "Morning_Sun" and sb also refers to "Morning_Sun". Line 5 prints "Morning_Sun".
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
