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…
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 = new int[2];
- Bint[] array; array = int[2];
- Cint array = new int[2];
- Dint array [2];
How the community answered
(51 responses)- A92% (47)
- B4% (2)
- C2% (1)
- D2% (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 neednew int[2]to instantiate an array. - C declares
arrayas a singleintprimitive, 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
Community Discussion
No community discussion yet for this question.