Java Arena
Step 1 of 6

Creating an array

A list grows as you add to it. An array is a simpler collection: you say how big it is when you create it, and that size never changes. In return, every place in it exists from the start, ready to use.

int[] numbers = new int[5];
numbers[2] = 7;
numbers[0] = 3;
System.out.println(numbers[0]);
System.out.println(numbers[2]);
System.out.println(numbers[4]);
Output
3
7
0
  • int[] is the type "array of ints". The square brackets make it an array.
  • new int[5] creates an array with room for five ints. Their indexes are 0 to 4, as in a list.
  • numbers[2] = 7; stores 7 at index 2. There's no add: the place is already there, and you assign to it.
  • numbers[2] reads the value at index 2, where a list would say list.get(2).

Index 4 was never given a value, and it holds 0. The array has exactly five places for as long as it exists: there's no way to make it hold a sixth value later.

Default values

A new array isn't empty: every element starts with a default value. It's 0 for int, 0.0 for double, false for boolean, and null for String. (null means "no value here yet".)

double[] prices = new double[3];
boolean[] done = new boolean[3];
String[] names = new String[3];
System.out.println(prices[0]);
System.out.println(done[1]);
System.out.println(names[2]);
Output
0.0
false
null

An element works like a variable

Each element behaves like a variable of the element type. You can use its value in a calculation, and change it with =, += or ++. The index can be any whole-number expression, such as a variable:

int[] goals = new int[3];
goals[1] = 2;
goals[1]++;
goals[0] = goals[1] * 2;
int last = 2;
goals[last] += 5;
System.out.println(goals[0] + " " + goals[1] + " " + goals[2]);
Output
6 3 5

Your task

Challenge 1 of 3

A parking garage has four levels, numbered 0 to 3. Fill in the blanks: make the array big enough for the four levels, and give level 3 its 20 free spots. Level 2 is never assigned, so it keeps the default value. The program prints:

Level 0: 12 free
Level 1: 5 free
Level 2: 0 free
Level 3: 20 free

Challenge 2

Read three whole numbers into an array of three ints: the first to index 0, the second to index 1 and the third to index 2. Then print the elements in the reverse order, from index 2 down to index 0. For the input 4, 9 and 1 the program prints:

1
9
4

Challenge 3

What does this program print? Keep track of each element, and remember the default value.