Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 201 ยท Arrays

Arrays

Learn Java arrays - declaring and creating them, indexes and length, default values, array literals, ArrayIndexOutOfBoundsException and why arrays are objects.

So far every variable you've written holds a single value: one int, one String, one boolean. Real programs juggle many values of the same kind. A week of temperatures, the scores of a class, the pixels of an image. Declaring temp1, temp2, ... temp7 doesn't scale, and you can't loop over seven separate names.

An array solves this. It's a single object that holds a fixed number of values of one type, stored side by side and numbered from 0. You pick any element by its number (its index), and a for loop can visit them all. Arrays are the most basic data structure in Java; ArrayList, String, HashMap and many other classes are built on top of them.

This lesson covers how to declare and create arrays, how indexes and length work, what values a new array starts with, what happens when you step outside its bounds, and the important fact that an array is an object, which changes how assignment works.

Declaring and creating an array

An array type is written as the element type followed by square brackets: int[] is "array of int", String[] is "array of String". Creating one takes the new keyword and a size:

Java
int[] temperatures = new int[7];      // room for 7 ints
String[] names = new String[3];       // room for 3 String references
double[] prices;                      // declared only, no array yet
prices = new double[100];             // created later

Three things are fixed the moment the array is created:

  • The element type. An int[] can only hold int values.
  • The length. An array of 7 always has 7 elements. It can't grow or shrink. (For a list that grows, you'll use ArrayList.)
  • The position of each element. Elements are numbered 0 to length - 1.

The size can be any int expression, including a variable or a value read at run time. It just can't be negative: new int[-1] throws NegativeArraySizeException. A length of 0 is allowed and surprisingly useful, for example as "no results".

Java also accepts the C-style form int temperatures[] = new int[7];, with the brackets after the name. It compiles, but every style guide prefers int[] temperatures, because the brackets are part of the type. You'll mostly see the old form in code ported from C.

Indexes and length

You read and write an element with array[index]. The first element is at index 0, the last at length - 1. The number of elements is the length field. Note that it's a field, not a method, so it has no parentheses (unlike String.length()).

Java Reading and writing elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

An element like temperatures[1] behaves exactly like a variable of the element type: you can assign to it, use ++ and compound assignment on it, and pass it to methods. The index can be any expression of type int (or a smaller integer type like char or short), which is what makes arrays work so well with loops:

Java
for (int day = 0; day < temperatures.length; day++) {
    IO.println("Day " + day + ": " + temperatures[day]);
}

The next lesson, Looping Through Arrays, is all about this pattern.

Default values

Look at Thursday in the example above: it prints 0, even though the program never stored anything there. When new creates an array, Java fills every element with the default value of its type. Unlike local variables, array elements are never "uninitialized".

Element type Default value
byte, short, int, long 0
float, double 0.0
char '\u0000' (the null character, not a space)
boolean false
any reference type (String, arrays, objects) null
Java What a new array contains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Arrays.toString turns an array into readable text like [0, 0, 0]. It lives in the Arrays class, which you'll explore later in this chapter. Compact source files (void main()) import it automatically; in a full class you'd add import java.util.Arrays;.

The null default for reference types matters. A new String[3] contains three empty slots, not three empty strings. Calling a method on one, such as labels[0].length(), throws a NullPointerException. You must put real objects into the slots first.

Array literals: create and fill in one step

When you already know the values, an array initializer creates the array, sizes it and fills it in one expression:

Java
int[] primes = { 2, 3, 5, 7, 11 };                // length 5
String[] weekdays = { "Mon", "Tue", "Wed", "Thu", "Fri" };
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

The braces-only form works only in a declaration. Anywhere else, such as when assigning to an existing variable, returning from a method or passing an argument, you need the full form new Type[] { ... }:

Java
int[] primes;
primes = { 2, 3, 5 };                 // compile error: illegal start of expression
primes = new int[] { 2, 3, 5 };       // fine

printAll(new String[] { "a", "b" });  // passing a fresh array to a method

Note that you can't give both a size and an initializer: new int[3] { 1, 2, 3 } is a compile error, because the length comes from the number of values. A trailing comma after the last value is allowed ({ 1, 2, 3, }), which keeps diffs clean when you list one value per line.

var works with the full form but not with the braces-only form, because a bare { ... } has no type of its own:

Java
var scores = new int[] { 90, 85 };    // fine: scores is int[]
var oops = { 90, 85 };                // compile error: cannot infer type for local variable oops

Going out of bounds

Java checks every array access at run time. An index below 0 or at or above length throws an ArrayIndexOutOfBoundsException and, if nothing catches it, stops the program. This check is one of Java's big safety features: in C, the same mistake silently reads or overwrites some other memory.

Java One past the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This example fails on purpose. The error message tells you exactly what went wrong: Index 3 out of bounds for length 3. When you see it, look at the loop or calculation that produced the index. The usual culprits are:

  • <= instead of < in a loop condition: for (int i = 0; i <= a.length; i++) touches index a.length.
  • Using length as an index: the last element is a[a.length - 1], never a[a.length].
  • Indexing an empty array: a[0] fails when a.length is 0, so check the length first.
  • Negative indexes from arithmetic, such as a[i - 1] when i is 0.

Don't catch this exception to "fix" a bad index. It signals a bug; correct the bounds instead.

Arrays are objects

An array isn't a primitive value, even an array of int. It's an object created on the heap, and the variable holds a reference to it, much like a String variable does. This has consequences that surprise many beginners.

Assignment copies the reference, not the array

Java Two variables, one array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

alias = original doesn't duplicate the three numbers. Both variables now point to the same array, so a change made through one is visible through the other. To get an independent array you must copy it explicitly, for example with clone() (shown above) or Arrays.copyOf. Looping Through Arrays covers the copying options in detail.

The same applies when you pass an array to a method: the method receives a copy of the reference, so it can change the caller's elements. You'll see exactly why in Parameters and Return Values.

== compares identity, not contents

Because array variables hold references, == asks "are these the same array object?", not "do these hold the same values?". Two separately created arrays with identical contents are not ==. Even a.equals(b) doesn't help: arrays inherit equals from Object, which also compares identity. To compare contents, use Arrays.equals(a, b):

Java Comparing arrays the right way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last two lines show the other side of the same coin. Printing an array directly gives something like [I@1b6d3586: the type code [I (array of int), an @ and a hash code in hex. That's the default Object.toString, and the hash part changes from run to run. Use Arrays.toString whenever you want to see the contents.

Other object-like behavior

  • An array variable can be null. int[] data = null; declares a reference to no array; data.length or data[0] then throws a NullPointerException. An empty array (new int[0]) and null are different things, and returning an empty array instead of null saves callers from null checks.
  • final applies to the reference, not the contents. final int[] limits = { 1, 2 }; stops you from assigning a different array to limits, but limits[0] = 50; is still allowed. Constants and final explains this in detail.
  • Arrays have the length field and a public clone() method, and they work anywhere an Object is expected.

Arrays of objects

An array of a reference type holds references. Each slot starts as null and must be filled before use:

Java
String[] guests = new String[3];
guests[0] = "Amara";
guests[1] = "Kenji";
// guests[2] is still null

for (String guest : guests) {
    IO.println(guest.toUpperCase());   // NullPointerException on the third guest
}

Two habits avoid this: create arrays with an initializer when you know the values, or check for null (and track how many slots you actually filled) when you fill them one by one.

When to use an array

Arrays are ideal when the number of elements is known up front and won't change: the 12 months, the squares on a chess board, the bytes of a file, a buffer of fixed size. They're also the fastest and most memory-efficient container Java has, especially for primitives: an int[] of a million elements stores the numbers directly, while a List<Integer> stores a million separate Integer objects.

When the size changes as the program runs (a shopping cart, a list of search results), use an ArrayList instead. It grows automatically and has methods for adding and removing.

More array programs to try

Once you have read about looping through arrays, methods and the Arrays class, come back and work through these classic exercises. They use ideas from those lessons (methods, Arrays helpers, one HashSet and one recursive method), so skim them now and run them again later. Each one is a short, complete program.

Sort in descending order, merge, and copy

Arrays.sort on an int[] only sorts ascending, and the Comparator that reverses the order works only on object arrays. So you either box the values into an Integer[], or sort ascending and read the array backwards. To merge two arrays that are not sorted, allocate one array of the combined length and copy both in with System.arraycopy; sort the result afterwards if you want it ordered.

Java Sort descending and merge unsorted arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Equality, common elements and removing every occurrence

== on two arrays asks "are these the same object?", and equals on an array does the same thing. To compare contents, write a loop or call Arrays.equals (one level) or Arrays.deepEquals (nested arrays). For common elements, put one array into a HashSet and keep what the other array shares with it, which avoids a nested loop. An array cannot shrink, so "remove all occurrences" means copying the values you keep into a new array of the right size.

Java Compare arrays, find common elements, remove a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The fifth line prints false even though the inner arrays look identical: Arrays.equals compares the two outer arrays element by element with equals, and each element is itself an array, so it compares identities. deepEquals descends into them.

Copy an array and search it recursively

Plain assignment copies the reference, not the data (you saw this in Arrays are objects). Real copies come from clone(), Arrays.copyOf (which can also grow or shrink), Arrays.copyOfRange and System.arraycopy. All of them are shallow: an array of arrays copies only the outer layer.

A recursive search solves a smaller version of the same problem. Linear search checks the first position and then asks the same question about the rest; binary search, which needs sorted data, looks at the middle and throws away half the array on each call. Both need a base case that stops the recursion (Recursion).

Java Copy arrays and search recursively

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that (low + high) >>> 1 computes the middle without overflowing for huge arrays, a bug that lived in the JDK's own binary search for years. For production code use Arrays.binarySearch; write your own only to learn or to practice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int[] a = new int[4]; a[1] = 7; IO.println(a[1] + a[3]);

    New int arrays are filled with 0, so a[3] is 0 and 7 + 0 is 7. Array elements always have a value.
  2. 2. For String[] s = { "x", "y", "z" };, which expression gives the last element?

    Indexes run from 0 to length - 1. s[s.length] and s[3] are one past the end and throw ArrayIndexOutOfBoundsException, and length is a field, not a method.
  3. 3. What does this print? int[] a = {1, 2}; int[] b = a; b[0] = 5; IO.println(a[0]);

    b = a copies the reference, so a and b point to the same array. Changing b[0] changes the element that a[0] also reads.
  4. 4. Which line compiles?

    The braces-only initializer is allowed only in a declaration with an explicit array type. Elsewhere you write new int[] { ... }, without a size.
  5. 5. Two arrays a and b were created separately and both contain 1, 2, 3. What is a == b?

    Arrays are objects, so == checks whether both variables point to the same array. a.equals(b) also compares identity; Arrays.equals compares the elements.

Summary

  • An array holds a fixed number of values of one type; declare it as Type[] name and create it with new Type[size] or an initializer { ... }.
  • Indexes run from 0 to length - 1; length is a field, not a method.
  • New arrays are filled with default values: 0, 0.0, false, '\u0000' or null.
  • The braces-only initializer works only in declarations; elsewhere write new Type[] { ... }.
  • Any index outside the bounds throws ArrayIndexOutOfBoundsException, which points to a bug in your bounds.
  • Arrays are objects: assignment copies the reference, == and equals compare identity, and printing one directly shows a type and hash code. Use clone(), Arrays.equals and Arrays.toString instead.

Next: Looping Through Arrays, where you'll sum, search, reverse and copy arrays with for and for-each loops.