Java · Beginner

Arrays in Java

9 min readUpdated September 24, 2026Every example verified

In short: A Java array holds a fixed number of values of one type in numbered slots starting at 0. int[] a = new int[5]; creates five ints set to 0, a.length gives the size, and reading or writing an index outside 0 to length-1 throws an ArrayIndexOutOfBoundsException.

Many values, one name

Five temperature readings could live in five variables, but then a loop cannot visit them and adding a sixth means editing every line that uses them. An array gives a whole sequence of values one name and lets code address each one by its position. The position is called the index, and it starts at 0: the first element of temps is temps[0] and the last is temps[temps.length - 1].

An array has one element type and one length, both fixed when it is created. int[] temps = {18, 21, 19, 24, 17}; creates and fills an array in one step when the values are known. new int[5] creates an array of five slots filled with the type's default: 0 for numbers, false for booleans, '\u0000' for chars and null for reference types such as String.

length is a field, not a method, so it has no parentheses; a String's length() does. Because the last valid index is length - 1, the standard counted loop is for (int i = 0; i < a.length; i++). When you only need each value and not its position, the enhanced for loop for (int t : temps) is shorter and cannot go out of bounds. Use the indexed form when you must write into the array or need the index itself.

An array is an object, and an array variable holds a reference to it. Assigning one array variable to another copies the reference, not the elements: both names now point at the same slots, and a change through one is visible through the other. To get an independent copy use Arrays.copyOf or the array's clone() method. The same rule explains why a method that receives an array can modify the caller's elements, which the methods lesson returns to.

The java.util.Arrays class provides the routine operations: Arrays.toString for readable printing, Arrays.sort to sort in place, Arrays.fill to set every element and Arrays.copyOf to copy or resize.

A two-dimensional array is an array whose elements are arrays. new int[3][4] makes three rows of four columns; seats[r][c] reaches one cell, seats.length is the number of rows and seats[r].length the number of columns in row r. Rows may even have different lengths. A nested loop over rows and columns visits every cell.

Because the size cannot change, arrays suit data whose count is known: days of a week, a fixed grid, n values announced at the top of the input. When elements come and go, ArrayList from the collections lesson grows on demand and is built on an array underneath.

Syntax

 Java · syntax
int[] a = new int[5];                // five zeros
int[] b = {18, 21, 19, 24, 17};      // create and fill
String[] names = new String[3];      // three nulls

a[0] = 42;                           // write; indexes run 0 .. a.length - 1
int first = b[0];                    // read
int n = b.length;                    // size, no parentheses

for (int i = 0; i < b.length; i++) { /* b[i] */ }   // with index
for (int value : b) { /* value */ }                 // each element in order

int[][] grid = new int[3][4];        // 3 rows, 4 columns; grid[r][c]

int a[] is also legal but int[] a is the conventional form: the type is "array of int". Import java.util.Arrays for Arrays.toString, Arrays.sort, Arrays.fill and Arrays.copyOf.

Creating, reading and looping

Five sensor readings: their count, first and last, an update, a sum and a maximum, then the defaults of freshly created arrays.

 Java
public class Main {
    public static void main(String[] args) {
        int[] temps = {18, 21, 19, 24, 17};
        System.out.println("Readings: " + temps.length);
        System.out.println("First: " + temps[0]);
        System.out.println("Last: " + temps[temps.length - 1]);
        temps[1] = 22;
        int sum = 0;
        int max = temps[0];
        for (int t : temps) {
            sum += t;
            if (t > max) {
                max = t;
            }
        }
        System.out.println("Sum: " + sum);
        System.out.println("Max: " + max);

        String[] names = new String[3];
        double[] prices = new double[2];
        System.out.println(names[0] + " " + prices[0]);
    }
}

Output

Readings: 5
First: 18
Last: 17
Sum: 100
Max: 24
null 0.0

temps.length is 5, so the last index is 4. After temps[1] = 22 the sum is 18 + 22 + 19 + 24 + 17. Starting max at the first element rather than at 0 keeps the search correct even if every reading were negative. The enhanced for loop visits the elements in order without an index. The final line shows the defaults: a String slot starts as null and a double slot as 0.0.

Filling from input, sorting, copying and aliasing

The first input value says how many parcel weights follow. The program is run with the input lines 4 and 12 7 30 7.

 Java
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] weights = new int[n];
        for (int i = 0; i < n; i++) {
            weights[i] = in.nextInt();
        }
        System.out.println(Arrays.toString(weights));
        Arrays.sort(weights);
        System.out.println(Arrays.toString(weights));
        System.out.println("Lightest: " + weights[0]);

        int[] copy = Arrays.copyOf(weights, weights.length);
        copy[0] = 99;
        System.out.println(weights[0] + " " + copy[0]);
        int[] alias = weights;
        alias[0] = 55;
        System.out.println(weights[0]);
    }
}

Input given to the program: 412 7 30 7

Output

[12, 7, 30, 7]
[7, 7, 12, 30]
Lightest: 7
7 99
55

Reading the count first lets the program size the array before filling it with an indexed loop. Arrays.toString prints the contents in brackets. Arrays.sort rearranges the array itself and returns nothing, so the smallest value is then at index 0. Arrays.copyOf makes an independent array: changing copy leaves weights alone. Plain assignment does not copy: alias and weights are two names for one array, so writing through alias changes what weights[0] reads.

A two-dimensional seating grid

Three rows of four seats, with three of them taken.

 Java
public class Main {
    public static void main(String[] args) {
        int[][] seats = new int[3][4];
        seats[0][2] = 1;
        seats[2][0] = 1;
        seats[2][3] = 1;
        int taken = 0;
        for (int r = 0; r < seats.length; r++) {
            for (int c = 0; c < seats[r].length; c++) {
                System.out.print(seats[r][c] == 1 ? "X" : ".");
                if (seats[r][c] == 1) {
                    taken++;
                }
            }
            System.out.println();
        }
        System.out.println("Taken: " + taken + " of " + (seats.length * seats[0].length));
    }
}

Output

..X.
....
X..X
Taken: 3 of 12

new int[3][4] gives twelve zeros; three cells are set to 1. The outer loop walks the rows and the inner loop the columns of the current row, printing one character per cell and a line break per row. seats.length counts rows and seats[r].length counts columns in that row, so the loop still works if the rows had different lengths.

Default element values

Element typeDefault in a new array
int, long, short, byte0
double, float0.0
booleanfalse
char'\u0000' (the null character)
String and every other reference typenull

Common mistakes

  • Looping up to and including length

    Why it goes wrong: for (int i = 0; i <= a.length; i++) reads a[a.length], one past the end, and throws ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5.

    Fix: Use <, or the enhanced for loop when the index is not needed.

     Java · fix
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
  • Mixing up length and length()

    Why it goes wrong: a.length() on an array fails with cannot find symbol: method length(), and s.length on a String fails the same way. Arrays expose a field; String has a method.

    Fix: Array: a.length. String: s.length(). An ArrayList uses size().

  • Printing an array with println

    Why it goes wrong: System.out.println(a) prints something like [I@1b6d3586: the element type and a hash code, because arrays do not override toString.

    Fix: Print Arrays.toString(a), or loop over the elements.

     Java · fix
    System.out.println(Arrays.toString(a));
  • Expecting = to copy an array

    Why it goes wrong: int[] backup = scores; creates a second reference to the same array. Sorting or overwriting through either name changes the one array both names share.

    Fix: Copy explicitly with Arrays.copyOf(scores, scores.length) or scores.clone().

Where you use this

Counting occurrences is a task arrays solve neatly. To tally how many customers gave each star rating from 1 to 5, create int[] counts = new int[6] and, for each rating r, do counts[r]++. The value itself is the index, so there is no searching; one pass over the input produces the whole histogram. The same trick counts letters of the alphabet with counts[ch - 'a'], or bus arrivals per hour of the day with an array of 24. Arrays also hold fixed tables, such as the days in each month, and grids such as a game board.

 Java · in practice
int[] counts = new int[6];
while (in.hasNextInt()) {
    int rating = in.nextInt();
    counts[rating]++;
}
for (int stars = 1; stars <= 5; stars++) {
    System.out.println(stars + " stars: " + counts[stars]);
}

Key points

  • An array has one element type and a fixed length; indexes run from 0 to length - 1.
  • new int[n] fills with zeros; reference arrays fill with null; {...} creates and fills at once.
  • a.length is a field with no parentheses; s.length() on a String is a method.
  • Use the indexed for to write or when the position matters; use for (T x : a) to read every element.
  • Assignment copies the reference; Arrays.copyOf or clone() copies the elements.
  • Arrays.toString, Arrays.sort, Arrays.fill and Arrays.copyOf cover the routine jobs.
  • A 2D array is an array of arrays: grid[r][c], grid.length rows, grid[r].length columns.

Try it yourself

The program reads five box weights into an array and prints the first one. Change it to count how many weights are greater than 10 and print that count. For the input 3 14 10 27 8 it should print 2.

Your program
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] boxes = new int[5];
        for (int i = 0; i < boxes.length; i++) {
            boxes[i] = in.nextInt();
        }
        System.out.println(boxes[0]);
    }
}
Input the program receives: 3 14 10 27 8
Expected output: 2

Practise this

Exercises for this lesson are in the Java practice set.

Open the Java playground

Frequently asked questions

Can I change the size of an array in Java?

No. The length is fixed when the array is created. To hold more, create a larger array and copy the elements across, which Arrays.copyOf(old, newLength) does in one call, then use the new array. When the number of elements changes often, use an ArrayList, which does that resizing for you.

Why do Java array indexes start at 0?

The index is the distance from the start of the array, so the first element is zero steps in. This convention, shared with C and most languages that followed it, is why the last index is length - 1 and why loops are written with i < a.length rather than <=.

What is the difference between an array and an ArrayList?

An array has a fixed length, can hold primitives such as int directly, and is accessed with a[i]. An ArrayList grows and shrinks as elements are added and removed, holds objects only (an Integer rather than an int), and is accessed with get(i), add(x) and size(). Arrays are lighter; lists are more convenient when the count varies.

Progress is stored only in this browser.

How this page was checked. Every program on it was run with OpenJDK 21 at build time by the publishing checks, and the output shown is what it printed. Running Java inside the browser is not available yet, so the Run button is absent rather than pretending; copy the code and run it with OpenJDK 21 locally.