nerdexam
Oracle

1Z0-808 · Question #86

Given: class X { static void m (int[] i) { i[0] += 7; } public static void main (String[] args) { int[] j = new int[1]; j[0] = 12; m(j); System.out.println(j[0]); } } What is the result?

The correct answer is C. 19. C is correct because Java arrays are objects passed by reference - when j is passed to m(), both i and j point to the same array in memory. So i[0] += 7 modifies the original array: 12 + 7 = 19. A (7) is wrong - the method adds 7 to the existing value, it doesn't replace it. B…

Working with Methods and Encapsulation

Question

Given: class X { static void m (int[] i) { i[0] += 7; } public static void main (String[] args) { int[] j = new int[1]; j[0] = 12; m(j); System.out.println(j[0]); } } What is the result?

Options

  • A7
  • B12
  • C19
  • DCompilation fails.
  • EAn exception is thrown at runtime.

How the community answered

(33 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    73% (24)
  • D
    15% (5)
  • E
    6% (2)

Explanation

C is correct because Java arrays are objects passed by reference - when j is passed to m(), both i and j point to the same array in memory. So i[0] += 7 modifies the original array: 12 + 7 = 19.

  • A (7) is wrong - the method adds 7 to the existing value, it doesn't replace it.
  • B (12) would be correct only if Java passed arrays by value (copying them), but it doesn't - the array reference is shared.
  • D (Compilation fails) is wrong - the code is syntactically valid Java.
  • E (Runtime exception) is wrong - j is a properly initialized array of length 1, so i[0] is a valid index.

Memory tip: Think of an array variable as a TV remote - passing it to a method gives that method its own copy of the remote, but both remotes still control the same TV. Changes to the TV (array contents) are visible everywhere.

Topics

#array-parameters#pass-by-value#method-calls#reference-types

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice