nerdexam
Oracle

1Z0-809 · Question #131

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 D. int [] array = new int [2]. Option D (int[] array = new int[2];) is the only choice that both declares the array type and allocates memory for it, which are both required before you can assign values to its elements. Why the others fail: A (int array[2]) - invalid Java syntax; the array size cannot go…

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 [2];
  • Bint array = new int [2] ;
  • Cint [] array;
  • Dint [] array = new int [2] ;

How the community answered

(24 responses)
  • A
    4% (1)
  • B
    17% (4)
  • C
    8% (2)
  • D
    71% (17)

Explanation

Option D (int[] array = new int[2];) is the only choice that both declares the array type and allocates memory for it, which are both required before you can assign values to its elements.

Why the others fail:

  • A (int array[2]) - invalid Java syntax; the array size cannot go inside the square brackets during declaration (unlike C/C++).
  • B (int array = new int[2]) - declares array as a plain int primitive, not an array; assigning new int[2] to it causes a type mismatch compile error.
  • C (int[] array) - correctly declares the variable as an int array, but never initializes it; attempting to use an uninitialized local variable is a compile error in Java.

Memory tip: Think of it as two jobs - the left side (int[] array) names the type and variable, while the right side (new int[2]) does the actual work of creating storage. In Java, you must do both jobs before touching the array - declaration without new leaves you with nothing to write to.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice