Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 85
Question ID: UKOCP78958
Consider below code of Test.java file:
- package com.udayankhattry.ocp;
- public class Test {
- public static void main(String[] args) {
- StringBuilder sb = new StringBuilder("Hakuna"); //Line n3
- change(sb); //Line n4
- System.out.println(sb); //Line n5
- }
- private static void change(StringBuilder s) {
- s.append("_Matata"); //Line n9
- }
- }
What will be the result of compiling and executing Test class?
- A Hakuna
- B _Matata
- C Hakuna_Matata
- D None of the other options
Reveal correct answer
Correct answer: C
Explanation
UKOCP78958:
At Line n3, 'sb' refers to StringBuilder object {"Hakuna"}.
When change method is called, both the variables 's' and 'sb' refer to same StringBuilder object {"Hakuna"}.
Line n9 modifies the passed object and appends "_Matata" to it. As a result, 's' now refers to "Hakuna_Matata" and 'sb' also refers to "Hakuna_Matata".
So, when control goes back to calling method main(String[]), Line n5 prints "Hakuna_Matata" on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
