1Z0-809 · Question #136
Given: ``java class Test { int al; public static void doProduct(int a) { a = a * a; } public static void doString(StringBuilder s) { s.append(" " + s); } public static void main(String[] args) {…
The correct answer is A. 10 Hello Hello 11. Option A is correct because Java passes primitives by value and objects by reference - but "by reference" means the reference itself is copied, not the object's address being rebindable. doProduct(i): Integer i is unboxed to a primitive int when passed. The method mutates only…
Question
class Test {
int al;
public static void doProduct(int a) {
a = a * a;
}
public static void doString(StringBuilder s) {
s.append(" " + s);
}
public static void main(String[] args) {
Test item = new Test();
item.al = 11;
StringBuilder sb = new StringBuilder("Hello");
Integer i = 10;
doProduct(i);
doString(sb);
doProduct(item.al);
System.out.println(i + " " + sb + " " + item.al);
}
}
What is the result?Options
- A10 Hello Hello 11
- B10 Hello Hello 121
- C100 Hello 121
- D10 Hello 11
- E100 Hello Hello 121
How the community answered
(30 responses)- A70% (21)
- B3% (1)
- C3% (1)
- D17% (5)
- E7% (2)
Explanation
Option A is correct because Java passes primitives by value and objects by reference - but "by reference" means the reference itself is copied, not the object's address being rebindable.
doProduct(i):Integer iis unboxed to a primitiveintwhen passed. The method mutates only its local copya, soistays10.doString(sb):StringBuilderis mutable and passed by reference, sos.append(" " + s)actually modifiessb. At call time,sevaluates to"Hello", so" " + s=" Hello", makingsbbecome"Hello Hello".doProduct(item.al):item.al(anint) is passed by value; the field stays11.
Why each distractor fails:
- B (
...121): Assumesitem.alwas modified - it wasn't; primitives are copied. - C (
100 Hello 121): Assumesichanged to 100 andsbwasn't modified - both wrong. - D (
10 Hello 11): AssumesStringBuilderwasn't modified - it was, becauseStringBuilderis a mutable object passed by reference. - E (
100 Hello Hello 121): Assumes bothianditem.alchanged - neither did.
Memory tip: Think "PRIM = private copy, Object = shared." Primitives (and unboxed wrappers like Integer) get their own copy in a method; mutable objects like StringBuilder share the underlying data, so changes inside a method stick.
Community Discussion
No community discussion yet for this question.