Arrays
Computer Science · Java
Question 1 of 10
0What does this Java code print? int[] a = {1, 9, 1}; System.out.println(a.length);
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Arrays explained
An array is an ordered collection of values stored under a single name, where each value is reached by its index. In most common languages, including Java, Python and JavaScript, the first index is 0, so an array with five items has indexes 0 to 4.
You read or change a value by putting its index in square brackets, such as scores[2]. Writing scores[2] = 7 replaces the value at position 2 and leaves every other value alone. Because the length is known, a loop can visit every item in turn by counting from 0 up to one less than the length.
Reading by index is very fast, because the computer can work out the position of any item directly. Inserting or deleting an item in the middle can be slower, because the items after it may need to be shifted along.
A common mistake is an off-by-one error, where a loop runs up to the length instead of one less than the length. It then asks for an index that does not exist, which usually makes the program crash.
Worked example
The array temps = [14, 9, 21, 17, 12] has indexes 0 to 4. What is total after this loop?
total = 0
for i from 0 to 4:
total = total + temps[i]
- The loop visits indexes 0, 1, 2, 3 and 4, so it adds all five values.
- The sum is .
- The average is .
Check: the length is 5, so the last index is .
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Java code print? int[] a = {7, 4, 8}; System.out.println(a.length);
Medium
What does this Java code print? int[] a = {4, 8, 2}; System.out.println(a[2]);
Hard
What does this Java code print? int[] a = {9, 4, 19, 13, 11}; int total = 0; for (int i = 0; i < a.length; i++) { total += a[i]; } System.out.println(total - a[4]);