java-arrays-unidimensionales

Arrays in Java: declaration, initialization, and traversal

  • 4 min

An array is a fixed-size structure that stores elements of the same type and identifies them by their index.

So far, if we wanted to store a number, we created a variable int a. If we wanted to store two, we did int b. But what if we want to store the grades of all 30 students in a class? Or the temperatures for each hour of the year?

We’re not going to create 30 variables (grade1, grade2, grade3…). That would be madness and impossible to maintain.

To solve this, we have Arrays. All their elements are grouped under a single reference.

Declaration and instantiation

To understand their declaration, let’s revisit what we learned about references.

In Java, an array is an object. It typically lives on the heap, and the variable we use to handle it holds a reference.

To create an array, we need two steps (which we sometimes do together):

Step a: declaration

We tell Java that this variable will point to an array of integers.

// Recommended syntax (type[] name)
int[] grades;

// C-inherited syntax (type name[]) - IT WORKS BUT AVOID IT
int gradesC[];
Copied!

At this point, grades is null. There’s no egg carton, just a label.

Step b: instantiation (memory allocation)

Here is where we use new to request space from the Heap. We must specify the fixed size.

grades = new int[5]; // We create an array of 5 slots
Copied!

All in one (the usual way)

int[] scores = new int[10];
Copied!

When you do this, Java reserves space for 10 integers and, very importantly, initializes them to their default value:

  • 0 for numbers (int, double…).
  • false for boolean.
  • null for objects (String, etc.).

Initializing with values

If you already know the values you want to put in from the start, Java provides a syntactic “shortcut” so you don’t have to go position by position.

// Java counts the elements and deduces that the size is 5
String[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
Copied!

This shortcut only works on the same line as the declaration.

Accessing elements

Arrays in Java have a 0-based index. This means the first element is at position 0, not 1.

If we have an array of size 5:

  • The first element is array[0].
  • The last element is array[4] (Size - 1).
int[] numbers = {10, 20, 30, 40, 50};

System.out.println(numbers[0]); // Prints 10
numbers[2] = 99;                // We change the 30 to a 99
Copied!

If you try to access numbers[5] in an array of size 5, Java will throw an exception and your program will crash. Unlike C++, Java checks the bounds for safety.

Traversing arrays

We have two main ways to iterate over an array.

Option a: classic for loop

It’s useful if you need to know the position (the index) or if you want to modify the array. To know the size of the array, we use the .length property (without parentheses, because it’s a final property, not a method).

int[] values = {10, 20, 30};

for (int i = 0; i < values.length; i++) {
    // We can use 'i' to print the position
    System.out.println("At position " + i + " there is a " + values[i]);

    // We could also modify it
    values[i] = values[i] * 2;
}
Copied!

If you only want to read the data and don’t care about the position, it’s much cleaner.

String[] fruits = {"Apple", "Pear", "Banana"};

for (String fruit : fruits) {
    System.out.println("I like " + fruit);
}
Copied!

Limitations of arrays

Arrays are very fast, but they have a major drawback: They are of fixed size.

Once you do new int[5], that array will always have 5 slots. You cannot add a sixth element. If you need more space, you would have to:

  1. Create a new, larger array.
  2. Copy the data from the old one to the new one.
  3. Throw away the old one.