Arrays ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-07-19

One-dimensional arrays

What is an array? It is a data structure available in almost every programming language that lets you store a group of values of the same type under a single common name. In this lesson we will look at one-dimensional arrays in Java: how to declare them, initialize them, get the array length, and iterate over the elements.

1. What Is an Array?

Imagine you run a shelter for stray animals that has five cats. You may not remember the name of each cat, but each one has a tag with a number that uniquely identifies it. You can think of this as an array named “cats” of size five. Note that indexing starts from zero — this is the convention in Java. Without the possibility to create arrays, you would have to declare five separate variables with different names, which is not very convenient.

Five cats with numbered tags as elements of a one-dimensional array in Java

In Java, you can create arrays of any dimension — one-dimensional, two-dimensional, three-dimensional, and so on. Let’s start with one-dimensional arrays.

2. Declaring an Array

A one-dimensional array in Java is a list of variables of the same type. To create an array, you first declare an array variable of the required type.

The general syntax for declaring a one-dimensional array looks like this:

type[] variableName;

The type parameter defines the element type of the array, also known as the base type. It can be a primitive type (int, double, boolean, etc.) or a reference type (for example, String).

You can place the square brackets either after the type or after the variable name. Placing them after the type is considered better style — the type and the brackets stay together, and it is immediately clear that the variable is an array of that type:

int monthDays[];        // legal, but not recommended
double[] monthSalaries; // recommended style

3. Initializing an Array with the new Keyword

Declaring an array doesn’t allocate memory for it. To allocate memory, use the new keyword, followed by the array type and its size in square brackets:

variableName = new type[size];

You can also declare and initialize an array in one line:

int[] values = new int[45];

Let’s look at an example that creates an int array of size 12. After the line int[] monthDays = new int[12]; executes, an array of 12 elements exists in memory. Each element is assigned the default value for its type:

Array base type Default value
byte, short, int, long 0
float, double 0.0
char '\u0000' (the null character)
boolean false
Reference types (String, etc.) null

To access an individual element, put its index in square brackets after the array name. This way you can both read and change the element’s value:

public class ArrayExample1 {
    public static void main(String[] args) {
        int[] monthDays = new int[12];
        monthDays[0] = 31;
        monthDays[1] = 28;
        monthDays[2] = 31;
        monthDays[3] = 30;
        monthDays[4] = 31;
        monthDays[5] = 30;
        monthDays[6] = 31;
        monthDays[7] = 31;
        monthDays[8] = 30;
        monthDays[9] = 31;
        monthDays[10] = 30;
        monthDays[11] = 31;
        System.out.println("April has " + monthDays[3] + " days.");
    }
}

The program prints: April has 30 days.

4. Array Initialization Block

If you already know the values for each element, use an array initialization block. Instead of new int[12], list the values in curly braces, separated by commas. The compiler infers the array size from the number of elements:

public class ArrayExample2 {
    public static void main(String[] args) {
        int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        System.out.println("April has " + monthDays[3] + " days.");
    }
}

5. Anonymous (Unnamed) Array

There is also a third form of creating an array — the anonymous array, also called an unnamed array. It is used in two scenarios.

First, suppose you declared and initialized an array testScores of size four, but later it needs to be replaced with an array of three elements. You can’t reuse the initializer syntax — it causes a compilation error:

int[] testScores = {1, 2, 3, 4};
...
testScores = {4, 7, 2}; // compilation error

Instead, use an anonymous array, which creates a new array in memory. Its syntax is a combination of the first two forms:

testScores = new int[]{4, 7, 2};

Second, anonymous arrays can be passed as method arguments. In the following example, the print method accepts an int array as a parameter, and an anonymous array is passed directly to the method:

public class ArrayExample3 {
    public static void main(String[] args) {
        int[] testScores = {1, 2, 3, 4};
        for (int element : testScores) {
            System.out.print(element + " ");
        }
        System.out.println();
        testScores = new int[]{4, 7, 2};
        for (int element : testScores) {
            System.out.print(element + " ");
        }
        System.out.println();

        print(new int[]{4, 6, 2, 3});
    }

    public static void print(int[] array) {
        for (int element : array) {
            System.out.print(element + " ");
        }
    }
}

6. Array Length and Iterating Over Elements

To get the array length (the number of its elements), use the length field:

int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
System.out.println(monthDays.length); // 12

Important

For arrays, length is a field, not a method: write it without parentheses. Don’t confuse it with length() on String and size() on collections — this small detail trips people up in interviews all the time.

The length field is handy for iterating over the elements in a for loop. Since indexing starts from zero, the index of the last element is length - 1:

int[] scores = {90, 75, 82, 68};
for (int i = 0; i < scores.length; i++) {
    System.out.println("Element at index " + i + ": " + scores[i]);
}

If you don’t need the index, iterate with a for-each loop — it is shorter and protects you from going out of the array bounds:

for (int score : scores) {
    System.out.println(score);
}

If you access a non-existent index (for example, scores[4] in an array of four elements), the compiler won’t report an error, but at runtime the program terminates with an ArrayIndexOutOfBoundsException.

Important

The size of a Java array is set at creation time and cannot be changed. If the number of elements is unknown in advance or needs to change, use a collection such as ArrayList.

For a deeper dive into array length — covering both one-dimensional and multidimensional arrays, with more examples — see the dedicated lesson “Length of Arrays”.

Frequently Asked Questions

Can I change the size of an array after it is created?

No, the array size is fixed at creation time. To “grow” an array, create a new, larger array and copy the elements into it (for example, with Arrays.copyOf). If the size needs to change often, an ArrayList is more convenient.

How do I print a one-dimensional array in Java?

The easiest way is System.out.println(Arrays.toString(array)) — the method returns a string like [1, 2, 3]. If you print the array directly with println(array), you will see something like [I@1b6d3586 instead of the elements — the object’s type and hash code. You can also loop over the elements with a for or for-each loop.

How do I reverse an array in Java?

The classic approach is a loop up to the middle of the array that swaps elements: the first with the last, the second with the second-to-last, and so on. For lists there is a ready-made method Collections.reverse(list), and an array of a reference type can be wrapped with Arrays.asList.

Comments

Please log in or register to have a possibility to add comment.