nerdexam
Oracle

1Z0-803 · Question #102

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. When an array is passed as an argument to a method, a copy of the reference to that array is passed, allowing modifications to the array's elements within the method to directly affect the original array object.

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

(17 responses)
  • A
    6% (1)
  • B
    12% (2)
  • C
    71% (12)
  • E
    12% (2)

Why each option

When an array is passed as an argument to a method, a copy of the reference to that array is passed, allowing modifications to the array's elements within the method to directly affect the original array object.

A7

The value 7 is added to the existing array element, not set as the new value of the element.

B12

The array element is modified within the `m` method, so its value is no longer 12 when printed.

C19Correct

The array `j` is initialized with `j[0] = 12`. When `m(j)` is called, the array reference is passed by value, meaning both `j` and the method parameter `i` refer to the same array object in memory. Inside `m`, `i[0] += 7` modifies the shared array object, changing `j[0]` from 12 to 19. Therefore, `System.out.println(j[0])` outputs 19.

DCompilation fails.

The provided code is syntactically correct and will compile without any errors.

EAn exception is thrown at runtime.

There are no operations in the code that would lead to a runtime exception, such as an `ArrayIndexOutOfBoundsException` or `NullPointerException`.

Concept tested: Array reference passing and modification in methods

Source: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html

Topics

#arrays#method parameters#pass by value#reference types

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice