Concepts / Array Initialization in Java

Array Initialization in Java

An array lets a program reach any element directly through its index, and Java indices start at 0.

  • Programming

Why Programs Need a Numbered Row of Slots

Many programs need to remember a list of values that arrive one at a time, such as numbers typed by a user. Each value has to be stored somewhere so that the program can use it later. An array is a natural place for this, because it is a numbered row of slots, and the program can reach any slot directly by its number.

The program this article builds does three things. It reads positive integers from the user until the user enters 0, it saves each number in an array, and then it prints the saved numbers from last to first. Before reading the explanation, make a prediction about the behavior.

What do you think happens?

If the user enters 7, then 12, then 4, then 0, in what order are the numbers printed?

  • 7, 12, 4

  • 4, 12, 7

  • 12, 7, 4

Reveal answer
Answer:

4, 12, 7

The program saves the numbers in the order they arrive and then prints from the last filled slot back to the first, so the last value entered (4) comes out first and the first value entered (7) comes out last.

Reaching a Slot Through Its Index

An array element is reached through its index, which is the slot's position in the row. Java indices start at 0, so the first slot is index 0, the second is index 1, and so on. An array with five slots therefore has indices 0 through 4. The index is what lets the program jump straight to any slot without looking at the slots before it.

nums[0]7nums[1]12nums[2]4nums[3]not yet fillednums[4]not yet filled
When the array holds five slots and only the first three hold saved input, which index reaches which slot, and which slots are still free?

The diagram shows that the first filled slot is index 0, not index 1. Because counting starts at 0, the last slot of a five-slot array is index 4, which is one less than the size. When the code writes nums[3], it reaches the fourth slot, the one labeled index 3 in the diagram, and nothing else.

java
Output
7
4
Notes on the code
  • nums[0] reaches the first slot directly, so the value 7 is stored there
  • nums[2] reaches the third slot, which holds 4
  • Indices run from 0 to 4 because the array has five slots

Declaring and Creating an Array with new

An array in Java is created in two steps that are often written together. The first step is a declaration, which names the array and states its element type. The second step is a creation, which reserves the space for the slots. The general pattern is a type followed by brackets, a name, and then new, followed by the type with a size in brackets.

int[]element type with bracketsmarking an arraynumsname that refers to thearray=connects the name to thenew arraynew int[5]creates the array with 5slots
In the statement int[] nums = new int[5]; which part declares the reference, which part creates the array object, and how do they connect?

The declaration gives the array a name, and the new expression creates the space that the name refers to. The two parts are joined by the equals sign. Read from left to right, the statement first says what kind of array the name will refer to, then builds the array itself.

The size is fixed when the array is created. Once the array exists, it cannot grow or shrink, so the size chosen must be large enough for the most data the program expects to store. The source program shows two real sizes. One array holds 365 boolean slots, one for each day of the year. Another holds 100 int slots, enough for up to 100 input numbers.

Counting Filled Slots with a Counter

A fixed-size array often holds fewer values than its size. The source program creates an array of 100 slots, but a user may enter only a handful of numbers. The physical size of the array is 100, while the logical size of the data is whatever the program has saved so far. A program that mixes these up will treat empty slots as real data.

The solution is a counter variable, named count in the source. The counter records how many slots are filled, and the filled slots are indices 0 through count minus 1. Each new value is stored at index count, and then count goes up by one, so the next value lands in the next free slot. Nothing is written past the end of the array.

Code walkthrough
int[] values = new int[5];
int count = 0;
int[] incoming = {7, 12, 4};
for (int k = 0; k < incoming.length; k++) {
    values[count] = incoming[k];
    count++;
}
System.out.println(count);
  1. 1
    Line 1 creates an array of five int slots, all empty for now.
  2. 2
    Line 2 sets the counter to 0, meaning no slots hold real data.
  3. 3
    Line 3 creates a small list of three incoming values for this example.
  4. 4
    Lines 4 to 7 loop over the incoming values. On each pass the current value goes into values[count], and then count increases by one.
  5. 5
    After the loop, count is 3, so the filled slots are indices 0, 1, and 2. Indices 3 and 4 still exist but are not part of the data.
  • values has 5 physical slots, but count starts at 0 to show that none are filled yet
  • Each value is stored at values[count], the next free slot
  • count++ moves the counter forward so the next value goes into the following slot
Output
3
Worked example

Finding the last filled index from the counter

An array has 5 slots. After the program has stored three values, count is 3. Which index holds the last saved value, and which slots are still free?

  1. 1
    Identify the filled slots

    The filled slots are indices 0 through count minus 1. With count equal to 3, that is indices 0, 1, and 2.

  2. 2
    Find the last filled index

    The last filled index is count minus 1, which is 2. The most recently saved value sits at index 2.

  3. 3
    Identify the free slots

    The array has indices 0 through 4, so the free slots are indices 3 and 4. The program must never read them as data.

Result

The last saved value is at index 2. Slots 3 and 4 are free, and the counter value 3 is one more than the last filled index.

Walking Backward Through the Filled Slots

To print the saved values in reverse order, the loop must start at the last filled index and move toward the first. The source describes this as a reverse loop that starts at count minus 1 and decrements to 0. It visits only the filled slots, last value first. The starting value is the only place where count appears, and that single line keeps the unused tail of the array out of the output.

i = 2prints 4i = 1prints 12i = 0prints 7i = -1condition i >= 0 fails,loop stopsi--i--i--
On each pass of a loop that starts at the last filled index and counts down, which index is visited, and when does the loop stop?
Code walkthrough
int[] values = {7, 12, 4, 0, 0};
int count = 3;
for (int i = count - 1; i >= 0; i--) {
    System.out.println(values[i]);
}
  1. 1
    The array holds five slots, but only the first three are filled according to count.
  2. 2
    The initializer i = count - 1 sets i to 2, so the first pass prints values[2], which is 4.
  3. 3
    The i-- step lowers i to 1 after each pass, so the second pass prints values[1], which is 12.
  4. 4
    After the third pass prints values[0], which is 7, i becomes -1. The condition i >= 0 is now false and the loop ends.
  5. 5
    The output is 4, then 12, then 7, the saved values in reverse order.
  • The loop starts at count - 1, which is index 2, the last filled slot
  • The condition i >= 0 is the stopping test for the front of the array
  • The unused slots at indices 3 and 4 are never visited
Output
4
12
7

Mistakes Beginners Make with Array Indices

  • Common mistake

    Assuming the first slot is index 1

    What it looks like

    Writing nums[1] = 7 and expecting it to fill the first slot of the array

    Why it fails

    Java indices start at 0, so the first slot is nums[0] and the value at nums[1] is the second slot

    Do this instead

    Use nums[0] for the first slot and remember that the last slot of a five-slot array is nums[4]

  • Common mistake

    Printing up to the array length instead of the counter

    What it looks like

    Looping from the last slot of a 100-slot array when only 3 numbers were saved

    Why it fails

    The array's physical size is 100, but only indices 0 through count minus 1 hold real data, so the loop prints empty slots

    Do this instead

    Start the reverse loop at count minus 1 and stop at 0

  • Common mistake

    Treating the array size as the number of saved values

    What it looks like

    Assuming an array of 100 slots holds 100 numbers after the user enters only 3

    Why it fails

    The size is fixed at creation and does not track how many slots are in use

    Do this instead

    Keep a separate counter such as count that records how many slots are filled

  • Common mistake

    Expecting an array to grow when it is full

    What it looks like

    Storing a 101st value in an array created with 100 slots

    Why it fails

    Once an array is created, its size cannot grow or shrink

    Do this instead

    Choose a size large enough for the most data you expect, and check the counter before storing

  • Common mistake

    Writing values[count] before checking that count is less than the array size

Trace It Yourself

EASY

An array is created with new int[6]. A program stores the values 9, 3, and 8 at indices 0, 1, and 2 using a counter, so count ends at 3. Write the output of a reverse loop that starts at count minus 1 and prints each filled slot. Then state which indices the loop never visits.

Hints
  • Count the filled slots using indices 0 through count minus 1
  • The reverse loop starts at index 2 and stops when i is no longer at least 0
  • The unused indices are 3, 4, and 5 because the array has six slots

Summary of Array Slots and Counters

  1. 1
    An array element is reached directly through its index, and Java indices start at 0, so a five-slot array uses indices 0 through 4
  2. 2
    An array is declared with a type and name, then created with new and a fixed size, and the size cannot change after creation
  3. 3
    A counter such as count records how many slots are filled, and the filled slots are indices 0 through count minus 1
  4. 4
    A reverse loop that starts at count minus 1 and decrements to 0 visits only the filled slots, last value first

At a glance

  • An array reaches any element directly through its index, and Java indices start at 0.
  • An array is declared with a type and name, then created with new and a size that is fixed at creation.
  • A counter such as count tracks how many slots hold real data, and those slots are indices 0 through count minus 1.
  • A reverse loop that starts at count minus 1 and stops at 0 prints only the filled slots, last value first.