Skip to content
Laviyx Learn

Try

Java course menu

Java Arrays: Creating, Looping, Sorting and the Arrays Class

Learn Java arrays: declaring and creating arrays, default values, indexing and length, ArrayIndexOutOfBoundsException, looping, printing with Arrays.toString, sorting, searching, copying and comparing arrays, and when to use ArrayList instead.

Beginner11 min readUpdated
On this page

An array stores a fixed number of values of the same type. Each value is an element, reached by its index, counting from 0. Arrays are the most basic way to hold a collection in Java; for collections that grow and shrink, you will use ArrayList.

Creating arrays#

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 88, 95, 64, 81};   // with values
        double[] prices = new double[3];       // 3 elements, all 0.0
        String[] names = new String[2];        // 2 elements, all null

        System.out.println(scores[0] + " " + scores[2]);
        System.out.println(scores.length);
        System.out.println(Arrays.toString(prices));
        System.out.println(Arrays.toString(names));
    }
}
Output
72 95
5
[0.0, 0.0, 0.0]
[null, null]
  • Type[] name declares an array; new Type[n] creates one with n elements.
  • New arrays are filled with default values: 0, 0.0, false, '\u0000' or null.
  • length is a field (no parentheses), and it never changes after creation.
  • Arrays.toString (from java.util.Arrays) formats an array for printing. Printing an array directly shows something like [I@1b6d3586, which is not useful.

Reading and changing elements#

Java
public class Main {
    public static void main(String[] args) {
        String[] days = {"Mon", "Tue", "Wed"};
        days[1] = "Tuesday";
        System.out.println(days[1]);
        System.out.println(days[days.length - 1]);   // last element
    }
}
Output
Tuesday
Wed

Out of bounds#

Java checks every index. Using an invalid one throws an exception instead of silently reading other memory:

Java
public class Main {
    public static void main(String[] args) {
        int[] values = {10, 20, 30};
        try {
            System.out.println(values[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Output
Error: Index 3 out of bounds for length 3

Valid indexes are 0 to length - 1.

Looping over an array#

Java
public class Main {
    public static void main(String[] args) {
        double[] temps = {31.5, 29.0, 33.5, 30.0};

        double sum = 0;
        for (double t : temps) {
            sum += t;
        }
        System.out.println("Average: " + sum / temps.length);

        for (int i = 0; i < temps.length; i++) {
            System.out.println("Day " + (i + 1) + ": " + temps[i]);
        }
    }
}
Output
Average: 31.0
Day 1: 31.5
Day 2: 29.0
Day 3: 33.5
Day 4: 30.0

The Arrays utility class#

java.util.Arrays has ready-made methods for common tasks:

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = {42, 7, 19, 3, 25};

        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));

        int index = Arrays.binarySearch(nums, 19);   // array must be sorted
        System.out.println("19 is at index " + index);

        int[] copy = Arrays.copyOf(nums, 3);          // first 3 elements
        int[] part = Arrays.copyOfRange(nums, 1, 4);  // indexes 1 to 3
        System.out.println(Arrays.toString(copy) + " " + Arrays.toString(part));

        int[] filled = new int[4];
        Arrays.fill(filled, 7);
        System.out.println(Arrays.toString(filled));

        System.out.println(Arrays.stream(nums).sum() + " " + Arrays.stream(nums).max().getAsInt());
    }
}
Output
[3, 7, 19, 25, 42]
19 is at index 2
[3, 7, 19] [7, 19, 25]
[7, 7, 7, 7]
96 42

Arrays are objects: copying and comparing#

An array variable holds a reference. Assigning it to another variable does not copy the array; both names refer to the same one. And == compares references, so use Arrays.equals to compare contents:

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = a;                  // same array
        int[] c = a.clone();          // a real copy

        b[0] = 100;
        System.out.println(a[0] + " " + c[0]);

        int[] d = {100, 2, 3};
        System.out.println((a == d) + " " + Arrays.equals(a, d));
    }
}
Output
100 1
false true

Finding the best element#

Java
public class Main {
    public static void main(String[] args) {
        int[] sales = {340, 120, 560, 410, 90, 560};

        int best = 0;
        for (int i = 1; i < sales.length; i++) {
            if (sales[i] > sales[best]) {
                best = i;
            }
        }
        System.out.println("Best day: " + (best + 1) + " with " + sales[best]);
    }
}
Output
Best day: 3 with 560

Using > (not >=) keeps the first best day when there is a tie.

Arrays or ArrayList?#

ArrayArrayList
SizeFixed at creationGrows and shrinks
Element typesPrimitives or objectsObjects only (Integer, not int)
Syntaxa[i], a.lengthlist.get(i), list.size()
HelpersArrays classMany methods built in

Use arrays when the size is fixed and known, or for primitive data where performance matters. Use ArrayList for most everyday collections.

Common mistakes#

Practice#

Practice exercise

Given int[] steps = {4200, 8100, 6700, 10200, 3900, 12000, 7600};, print the total, the average as a decimal, and how many days reached at least 8000 steps.

Show solution
Java
public class Steps {
    public static void main(String[] args) {
        int[] steps = {4200, 8100, 6700, 10200, 3900, 12000, 7600};

        int total = 0;
        int goalDays = 0;
        for (int s : steps) {
            total += s;
            if (s >= 8000) goalDays++;
        }

        System.out.println("Total: " + total);
        System.out.printf("Average: %.2f%n", (double) total / steps.length);
        System.out.println("Goal reached on " + goalDays + " days");
    }
}
Output
Total: 52700
Average: 7528.57
Goal reached on 3 days

Practice exercise

Reverse int[] a = {1, 2, 3, 4, 5, 6}; in place by swapping elements from both ends, then print it with Arrays.toString.

Show solution
Java
import java.util.Arrays;

public class Reverse {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6};
        for (int left = 0, right = a.length - 1; left < right; left++, right--) {
            int temp = a[left];
            a[left] = a[right];
            a[right] = temp;
        }
        System.out.println(Arrays.toString(a));
    }
}
Output
[6, 5, 4, 3, 2, 1]

Key takeaway#

Finished this lesson?