nerdexam
Oracle

1Z0-811 · Question #60

Given the code fragment: int[] arr1 = {1, 2, 3}; int[] arr2 = new int[2]; arr2[0] = 10; System.out.print(arr1.length + " : " + arr2.length); What is the result?

The correct answer is B. 3:2. Option B is correct because arr1 is initialized with 3 elements {1, 2, 3}, giving it a length of 3, while arr2 is explicitly allocated with new int[2], giving it a length of 2 - so the output is 3 : 2. Option A is wrong because arr2.length is 2, not 1; assigning a value to…

Arrays and Logic

Question

Given the code fragment: int[] arr1 = {1, 2, 3}; int[] arr2 = new int[2]; arr2[0] = 10; System.out.print(arr1.length + " : " + arr2.length); What is the result?

Options

  • A3:1
  • B3:2
  • C0:1
  • D2:0

How the community answered

(43 responses)
  • B
    95% (41)
  • C
    2% (1)
  • D
    2% (1)

Explanation

Option B is correct because arr1 is initialized with 3 elements {1, 2, 3}, giving it a length of 3, while arr2 is explicitly allocated with new int[2], giving it a length of 2 - so the output is 3 : 2. Option A is wrong because arr2.length is 2, not 1; assigning a value to arr2[0] does not shrink the array. Options C and D are wrong because .length reflects the allocated size at creation time, not how many elements have been assigned non-default values - arr1 starts with 3 elements and arr2 was allocated with 2 slots, neither is 0.

Memory tip: Think of new int[2] as reserving 2 parking spaces - the spaces exist whether or not a car is parked in them. .length counts spaces, not cars.

Topics

#array initialization#array length property#array syntax

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice