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
- public class Test {
- public static void main (String[] args) {
- // insert code here
- array[0]=10;
- array[1]=20;
- System.out.print(array[0]+":"+array[1]);
- }
- } 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)- A4% (1)
- B17% (4)
- C8% (2)
- D71% (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]) - declaresarrayas a plainintprimitive, not an array; assigningnew 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.