An array in Java is a fixed-length container that holds values of one type, accessed by a zero-based index. Declare it with int[] scores;, create it with scores = new int[5]; or int[] scores = {90, 85, 70};, and walk through it with a for loop up to scores.length.
This guide covers the whole life of an array: declaring, creating, filling, reading, looping, copying and the errors beginners hit first. Every claim is checked against the Java Tutorials, the Java Language Specification (JLS) and the java.util.Arrays API documentation. The examples use Java 8 syntax or later.
How to declare an array in Java
An array type is written as the element type followed by square brackets. A declaration only tells the compiler that the variable will refer to an array. It does not create the array.
int[] scores;
String[] names;
double[] prices;
Java also accepts the brackets after the variable name, as in int scores[];. The Java Tutorials discourage it, because the brackets are part of the type, and keeping them next to the type makes that visible. Use int[] scores.
If you try to use a declared variable before creating the array, the compiler stops you with an error such as variable scores might not have been initialized. The exact wording depends on the compiler version.
How to create and initialize an array
There are two ways to create an array. The first allocates space with new and a length, and you fill in the values afterwards:
int[] scores = new int[5]; // five ints, all 0
scores[0] = 90;
scores[1] = 85;
scores[4] = 70;
The second is an array initializer: a comma-separated list of values in braces. The length is the number of values you list.
int[] scores = {90, 85, 70};
String[] names = {"Ada", "Grace", "Linus"};
The brace-only form works in a declaration. If you want to assign an initializer to an existing variable later, or pass one to a method, you need new with the type:
scores = new int[] {90, 85, 70};
The JLS also says a trailing comma after the last value in an initializer is allowed and ignored, so {1, 2, 3,} compiles and has three elements.
Default values
When you create an array with new, the JLS says each component is initialized to the default value of its type. In practice that means:
| Element type | Default value |
|---|---|
int, long, short, byte | 0 |
double, float | 0.0 |
boolean | false |
char | the null character, '\u0000' |
any object type, such as String | null |
The last row catches people out. new String[3] holds three null references, not three empty strings, so calling names[0].length() on it throws a NullPointerException until you assign a real string.
Reading, writing and the length of an array
Elements are addressed by index, starting at 0. An array of 10 elements has valid indexes 0 through 9. Reading and writing both use square brackets:
int[] scores = {90, 85, 70};
int first = scores[0]; // 90
scores[2] = 75; // the array is now {90, 85, 75}
int count = scores.length; // 3
length is a public final field of every array, so it has no parentheses. The JLS states that once an array object is created, its length never changes. That is the main limit of arrays: you cannot add or remove elements, only replace them.
Arrays are also objects. A variable of type int[] holds a reference, so assigning one array variable to another does not copy the data:
int[] a = {1, 2, 3};
int[] b = a; // b points at the same array
b[0] = 99;
System.out.println(a[0]); // 99
How to loop through an array in Java
The classic way is an indexed for loop that runs while the index is less than length. Use it when you need the index, or when you want to change elements.
int[] scores = {90, 85, 70};
for (int i = 0; i < scores.length; i++) {
System.out.println(i + ": " + scores[i]);
}
Example output:
0: 90
1: 85
2: 70
When you only need each value, the enhanced for loop (also called for-each) is shorter and removes the chance of an off-by-one mistake:
int total = 0;
for (int score : scores) {
total += score;
}
System.out.println(total); // 245
The loop variable in a for-each is a copy of the element for primitive types, so assigning to score inside the loop does not change the array. Use the indexed form to modify elements. The syntax of both loops, plus break and continue, is covered in For Loop in Java: Syntax, Examples and the Enhanced For.
You can also stream an array. Arrays.stream(scores).sum() returns the same 245 without writing the loop, and Arrays.stream is documented to work on arrays of int, long, double and objects.
Two-dimensional arrays
A multidimensional array in Java is an array of arrays, declared with one pair of brackets per dimension. You need one index per dimension to reach a single element.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // 6
System.out.println(grid.length); // 2 rows
System.out.println(grid[0].length); // 3 columns in row 0
Because each row is its own array, rows can have different lengths. The Java Tutorials show this with a String[][] whose first row has three entries and whose second row has two. Loop over a grid with nested loops, using each row's own length:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
You can also create a grid with new int[3][4], which makes three rows of four zeros each.
Useful methods in java.util.Arrays
Arrays themselves have no methods besides those inherited from Object, so sorting, searching and printing live in the helper class java.util.Arrays. Add import java.util.Arrays; at the top of your file.
| Method | What it does |
|---|---|
Arrays.toString(a) | Returns a readable string such as [1, 3, 5] |
Arrays.deepToString(a) | The same for nested arrays, such as [[1, 2], [3]] |
Arrays.sort(a) | Sorts into ascending order, in place |
Arrays.fill(a, value) | Sets every element to one value |
Arrays.copyOf(a, newLength) | Returns a new array, truncated or padded with default values |
Arrays.copyOfRange(a, from, to) | Copies a slice; from is inclusive, to is exclusive |
Arrays.equals(a, b) | True if both arrays have the same length and equal elements in order |
Arrays.binarySearch(a, key) | Finds the index of a value; the array must already be sorted |
Use Arrays.toString whenever you want to print an array. Passing an array straight to System.out.println prints a type code and a hash, such as [I@1b6d3586, not the contents. Likewise, a.equals(b) on two arrays compares references, not contents, so use Arrays.equals(a, b).
import java.util.Arrays;
int[] a = {5, 3, 1};
Arrays.sort(a);
System.out.println(Arrays.toString(a)); // [1, 3, 5]
System.out.println(Arrays.binarySearch(a, 3)); // 1
int[] bigger = Arrays.copyOf(a, 5);
System.out.println(Arrays.toString(bigger)); // [1, 3, 5, 0, 0]
binarySearch returns -(insertion point) - 1 when the key is not found, so a negative result means "absent". If the array is not sorted first, the result is undefined.
How to copy an array
As shown above, int[] b = a; copies only the reference. For a real copy, use Arrays.copyOf or Arrays.copyOfRange, or System.arraycopy when you want to copy into an array that already exists:
int[] source = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOf(source, source.length); // full copy
int[] middle = Arrays.copyOfRange(source, 1, 4); // {20, 30, 40}
int[] target = new int[5];
System.arraycopy(source, 2, target, 0, 3); // target: {30, 40, 50, 0, 0}
The parameters of System.arraycopy are source array, source start position, destination array, destination start position and number of elements. These copies are shallow: for an array of objects, both arrays end up pointing at the same objects.
Common array errors
ArrayIndexOutOfBoundsException
The JLS says every array access is checked at run time, and an index less than zero or greater than or equal to the length throws ArrayIndexOutOfBoundsException. The usual cause is a loop that uses <= instead of <:
int[] scores = {90, 85, 70};
for (int i = 0; i <= scores.length; i++) { // bug: should be <
System.out.println(scores[i]);
}
Example output (the message wording can differ between Java versions):
90
85
70
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
The last valid index is always length - 1. A for-each loop avoids this error entirely.
NullPointerException on an array or an element
This happens in two ways. The array variable itself may be null because you declared it but never assigned new, as a class field might be. Or the array exists but an object element is still null, as with new String[3] described earlier.
ArrayStoreException
Java arrays are covariant: a String[] can be assigned to an Object[] variable. The JLS notes that storing a value of the wrong type through such a variable compiles but throws ArrayStoreException at run time. It is rare in beginner code, but it explains why generic collections are usually preferred when types get mixed.
Using the wrong index type
Array indexes must be int or a type that promotes to int (short, byte, char). A long index is a compile-time error.
When to use an ArrayList instead
Use an array when the size is known up front and fixed, when you hold primitives such as int or double in bulk, or when a method signature (such as main(String[] args)) requires one. Use java.util.ArrayList when you need to add or remove items after creation. If you do need to convert, Arrays.asList(array) returns a fixed-size list backed by the array: writes go through to the array, but add and remove are not supported.
Frequently asked questions
- Can you change the size of an array in Java?
- No. The length of a Java array is fixed when the array is created and never changes. To get a bigger array, create a new one and copy the old values into it, for example with Arrays.copyOf(old, newLength). If you need a collection that grows, use java.util.ArrayList instead.
- What is the default value of an array element in Java?
- Every element of a newly created array is set to the default value of its type. Numeric types start at zero, boolean starts at false, and object types such as String start at null. This is why new String[3] gives you three null references, not three empty strings.
- What is the difference between length and length() in Java?
- An array has a final field called length, written without parentheses: names.length. A String has a method called length(), written with parentheses: text.length(). Mixing them up is a compile error.
- How do you print an array in Java?
- Passing an array straight to System.out.println prints a type code and hash, such as [I@1b6d3586, not the contents. Use Arrays.toString(array) for a one-dimensional array, which gives output like [1, 2, 3], or Arrays.deepToString(array) for nested arrays.