nerdexam
Oracle

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

Given:
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)
  • A
    70% (21)
  • B
    3% (1)
  • C
    3% (1)
  • D
    17% (5)
  • E
    7% (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 i is unboxed to a primitive int when passed. The method mutates only its local copy a, so i stays 10.
  • doString(sb): StringBuilder is mutable and passed by reference, so s.append(" " + s) actually modifies sb. At call time, s evaluates to "Hello", so " " + s = " Hello", making sb become "Hello Hello".
  • doProduct(item.al): item.al (an int) is passed by value; the field stays 11.

Why each distractor fails:

  • B (...121): Assumes item.al was modified - it wasn't; primitives are copied.
  • C (100 Hello 121): Assumes i changed to 100 and sb wasn't modified - both wrong.
  • D (10 Hello 11): Assumes StringBuilder wasn't modified - it was, because StringBuilder is a mutable object passed by reference.
  • E (100 Hello Hello 121): Assumes both i and item.al changed - 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.

Full 1Z0-809 Practice