AP Computer Science A · Topic 6.1
Array Creation and Access Practice
Part of Array.
Practice questions
24
Sample questions
5 of 24 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 1/5
int[] a = new int[5]; int sum = 0; for (int x : a) { sum += x; } System.out.println(sum);What is printed?
- A
ArrayIndexOutOfBoundsException
- B
5
- C
null
- Dcheck_circle
0
Why
new int[5] initializes all 5 elements to 0. Their sum is 0.
- A
Sample 2difficulty 2/5
For <code>int[] a = {10, 20, 30};</code>, <code>a[1]</code> is
- Acheck_circle
20
- B
Out of bounds
- C
10
- D
30
Why
Index 1 is the SECOND element (20).
- A
Sample 3difficulty 2/5
int[] a; a[0] = 1;What is wrong?
- A
Arrays cannot be declared without size
- B
Index 0 is reserved
- C
Nothing is wrong
- Dcheck_circle
a is declared but not instantiated; you must allocate with new int[size]
Why
Declaring int[] a only creates a reference variable. You must allocate the array with a = new int[n] before assigning elements.
- A
Sample 4difficulty 2/5
int[] a = {10, 20, 30, 40}; System.out.println(a[2]);What is printed?
- Acheck_circle
30
- B
20
- C
40
- D
2
Why
Arrays are 0-indexed, so a[0]=10, a[1]=20, a[2]=30, a[3]=40. Index 2 is the third element, 30.
- A
Sample 5difficulty 2/5
int[] a = {3, 1, 4, 1, 5}; System.out.println(a.length);What is printed?
- A
4
- B
6
- C
0
- Dcheck_circle
5
Why
The initializer list has 5 elements, so a.length is 5. Note: array length uses the field a.length (no parentheses), not the method a.length().
- A