An array stores a fixed number of values of the same type, one after another, under a single name. Instead of separate variables called score1, score2 and score3, you write one array called scores and reach each value by its position. You met arrays briefly in the loops lesson; this lesson covers them properly.
Arrays are the most basic collection in Java and they're very fast. Their one limitation is that the size is fixed when the array is created. If you need a list that grows and shrinks, the ArrayList lesson shows the flexible alternative, but arrays remain everywhere: in method parameters like String[] args, in performance-sensitive code and as the building block underneath many other collections.
In this lesson you'll create arrays, understand default values, loop through them, sort and print them with the Arrays class, copy them correctly and build two-dimensional grids.
Creating arrays
There are two ways to create an array:
int[] scores = {72, 88, 95, 60}; // values known now
double[] prices = new double[5]; // 5 slots, filled with defaults- The type is followed by
[]:int[]means "array of int". - With
new type[size], every element starts with a default value:0for numbers,falsefor booleans,'\u0000'for chars andnullfor objects such as Strings. array.lengthgives the size. Note there are no brackets:lengthis a field, not a method likeString.length().- Valid indexes run from
0tolength - 1. Anything else throwsArrayIndexOutOfBoundsException.
Looping through arrays
Use an index-based for loop when you need positions or want to change elements, and the enhanced for loop when you just need each value:
for (int i = 0; i < scores.length; i++) {
scores[i] += 5; // change each element
}
for (int s : scores) {
System.out.println(s); // read each element
}Changing the loop variable in an enhanced for loop, s += 5, does not change the array, because s is a copy of each value. That's a common surprise.
The Arrays helper class
java.util.Arrays provides ready-made tools for arrays:
| Method | What it does |
|---|---|
Arrays.toString(a) | Text such as [72, 88, 95] for printing |
Arrays.sort(a) | Sorts the array in place, smallest first |
Arrays.fill(a, 0) | Sets every element to a value |
Arrays.copyOf(a, n) | A new array with the first n elements |
Arrays.equals(a, b) | true if both hold the same values in the same order |
Arrays.binarySearch(a, x) | Fast search in a sorted array |
Printing an array directly with System.out.println(a) shows something like [I@1b6d3586, its type and memory hash, which is rarely what you want. Use Arrays.toString(a) instead.
Copying and 2D arrays
Assigning one array variable to another, int[] b = a;, does not copy the array. Both names now point to the same array, so changing b[0] also changes a[0]. To get an independent copy, use Arrays.copyOf(a, a.length) or a.clone().
A two-dimensional array is an array of arrays, perfect for grids, tables and game boards:
int[][] grid = new int[3][4]; // 3 rows, 4 columns
grid[1][2] = 7; // row 1, column 2grid.length is the number of rows and grid[0].length the number of columns. Nested loops visit every cell.
Arrays and methods
Arrays are objects, so a method receives a reference to the same array, not a copy. A method can therefore change the caller's array:
static void doubleAll(int[] values) {
for (int i = 0; i < values.length; i++) {
values[i] *= 2;
}
}After doubleAll(scores), every element of scores has doubled. This is useful, but it can surprise callers, so name such methods clearly and document that they modify their argument. A method can also create and return a new array, static int[] firstThree(int[] a) { return Arrays.copyOf(a, 3); }, which leaves the original untouched.
The array operations and sorting and multidimensional arrays lessons build on these basics.
Java Arrays Syntax
Array syntax
type[] name = {v1, v2, v3};
type[] name = new type[size];
name[index] = value;
name.length
import java.util.Arrays;
Arrays.sort(name);
Arrays.toString(name);
type[][] grid = new type[rows][cols];
grid[r][c] = value;Java Arrays Summary
int[] a = {1, 2, 3};ornew int[size]; the size can't change later.- New arrays are filled with defaults: 0, false or null.
- Indexes run from 0 to
a.length - 1;lengthhas no brackets. Arrays.toString,sort,fill,copyOfandequalssave a lot of code.b = ashares one array; copy withArrays.copyOf. 2D arrays are arrays of arrays.
Java Arrays Examples
Each example shows the code, the output it produces and what each part does.
Test scores
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {72, 95, 61, 88, 79};
int total = 0;
for (int s : scores) {
total += s;
}
double average = (double) total / scores.length;
Arrays.sort(scores);
System.out.println("Sorted: " + Arrays.toString(scores));
System.out.println("Lowest: " + scores[0] + ", highest: " + scores[scores.length - 1]);
System.out.printf("Average: %.1f%n", average);
}
}Sorted: [61, 72, 79, 88, 95]
Lowest: 61, highest: 95
Average: 79.0Line-by-line explanation
- Lines 8 to 10The enhanced for loop adds up every score.
- Line 11Casting to double before dividing keeps the decimal part.
- Line 13Arrays.sort reorders the array itself.
- Line 15After sorting, the first and last elements are the extremes.
Defaults and the sharing trap
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = new String[3];
boolean[] done = new boolean[3];
System.out.println(Arrays.toString(names) + " " + Arrays.toString(done));
int[] original = {1, 2, 3};
int[] alias = original;
int[] copy = Arrays.copyOf(original, original.length);
alias[0] = 99;
System.out.println(Arrays.toString(original));
System.out.println(Arrays.toString(copy));
}
}[null, null, null] [false, false, false]
[99, 2, 3]
[1, 2, 3]Line-by-line explanation
- Lines 5 to 6New arrays are filled with default values.
- Line 10alias points to the same array as original.
- Line 11copy is a separate array with the same values.
- Lines 13 to 15Changing alias changes original, but copy is untouched.
A small 2D grid
public class Main {
public static void main(String[] args) {
char[][] board = new char[3][3];
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[r].length; c++) {
board[r][c] = '.';
}
}
board[0][0] = 'X';
board[1][1] = 'O';
board[2][0] = 'X';
for (char[] row : board) {
System.out.println(new String(row));
}
}
}X..
.O.
X..Line-by-line explanation
- Line 3Three rows of three chars, like a noughts and crosses board.
- Lines 4 to 8Nested loops fill every cell with a dot.
- Lines 9 to 11Place three moves using row and column indexes.
- Lines 13 to 15Each row is a char array, which new String(...) turns into text.
Common Java Arrays Mistakes
Using <= with length
for (int i = 0; i <= scores.length; i++) {
System.out.println(scores[i]); // ArrayIndexOutOfBoundsException
}for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}Printing an array directly
System.out.println(scores); // [I@6d06d69cSystem.out.println(Arrays.toString(scores)); // [72, 88, 95]Expecting = to copy an array
int[] backup = scores;
scores[0] = 0; // backup[0] is now 0 tooint[] backup = scores.clone();
scores[0] = 0; // backup is unchangedJava Arrays in Real Projects
Arrays in practice
Image-processing code stores pixels in large 2D arrays, games keep their boards and maps in grids, and the String[] args in every main method is an array of the words typed after the program name on the command line. Many higher-level collections, including ArrayList, use an array internally.
Java Arrays FAQ
How do I find the length of an array in Java?
Use the length field without brackets: scores.length. For a 2D array, grid.length gives the number of rows and grid[0].length the number of columns in the first row. Strings use the method length() and lists use size().
Can a Java array change size?
No. The size is fixed when the array is created. To "grow" an array, create a bigger one and copy the old values across, for example scores = Arrays.copyOf(scores, scores.length * 2);. If the size changes often, use an ArrayList.
How do I print a 2D array?
Arrays.toString only prints the outer array, which shows the memory codes of the rows. Use Arrays.deepToString(grid), which prints [[1, 2], [3, 4]], or nested loops for a neatly formatted grid.
How do I sort an array in descending order?
For an array of objects such as Integer[] or String[], use Arrays.sort(arr, Collections.reverseOrder()). For a primitive int[], sort it with Arrays.sort(arr) and then read or reverse it from the end.
How do I convert an array to a list?
Arrays.asList(arr) gives a fixed-size list backed by an object array: you can change elements but not add or remove them. List.of(...) gives an unchangeable list, and new ArrayList<>(Arrays.asList(arr)) gives a list you can change freely.
Java Arrays Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the line so it prints the number of elements.
int[] nums = {4, 8, 15};
System.out.println(nums.);
What does this print?
double[] d = new double[2];
System.out.println(d[1]);
What does this print?
int[] a = {3, 1, 2};
int[] b = a;
Arrays.sort(b);
System.out.println(Arrays.toString(a));
What does this print?
int[][] g = {{1, 2, 3}, {4, 5, 6}};
System.out.println(g.length + " " + g[1][2]);
Which line creates an independent copy of int[] a?
Java Arrays Quiz
5 questions to check what you learned.
What is the last valid index of an array with 10 elements?
- 9
- 10
- 11
- 1
What is the default value in a new
String[]array?- ""
- "null"
- 0
- null
Which method turns an array into readable text?
- a.toString()
- Arrays.toString(a)
- String.valueOf(a)
- a.print()
Can the size of a Java array change after it's created?
- Yes, with add()
- Only for int arrays
- Only if it's empty
- No, its length is fixed
Why doesn't
for (int s : scores) s *= 2;double the array's values?- Enhanced for loops can't do maths
- scores must be final
- s is a copy of each value, so changing it doesn't affect the array
- It only works on ArrayList