nerdexam
Oracle

1Z0-808 · Question #5

Given the code fragment: 1. public class Test { 2. public static void main(String[] args) { 3. / insert code here / 4. array[0]=10; 5. array[1]=20; 6. System.out.print (array[0]+":"+array[1]); 7. }…

The correct answer is A. int[] array = new int[2]. Option A (int[] array = new int[2];) is correct because it both declares an array reference (int[] array) and instantiates it with new int[2], allocating two integer slots - exactly what's needed before assigning array[0] and array[1]. Why the distractors fail: B is invalid…

Creating and Using Arrays

Question

Given the code fragment:
  1. public class Test {
  2. public static void main(String[] args) {
  3. /* insert code here */
  4. array[0]=10;
  5. array[1]=20;
  6. System.out.print (array[0]+":"+array[1]);
  7. }
  8. } Which code fragment, when inserted at line 3, enables the code to print 10:20?

Options

  • Aint[] array = new int[2];
  • Bint[] array; array = int[2];
  • Cint array = new int[2];
  • Dint array [2];

How the community answered

(51 responses)
  • A
    92% (47)
  • B
    4% (2)
  • C
    2% (1)
  • D
    2% (1)

Explanation

Option A (int[] array = new int[2];) is correct because it both declares an array reference (int[] array) and instantiates it with new int[2], allocating two integer slots - exactly what's needed before assigning array[0] and array[1].

Why the distractors fail:

  • B is invalid syntax - array = int[2]; is not legal Java; you need new int[2] to instantiate an array.
  • C declares array as a single int primitive, not an array; you can't index a primitive with [0] or [1].
  • D is not valid Java syntax at all - Java does not support C-style int array[2]; declarations with a size inside the brackets.

Memory tip: In Java, the [] belongs with the type, not the variable name, and arrays always require new Type[size] to actually exist in memory - declaration alone just creates a null reference.

Topics

#array declaration#array initialization#new keyword#syntax

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice