Java Arrays
Java arrays store a fixed number of values of the same type in a single variable. Each value has an index starting at 0, and the size is set when the array is created and cannot change.
Creating and Accessing Arrays
public class Main {
public static void main(String[] args) {
int[] temps = {31, 28, 35, 30};
String[] names = new String[3]; // three empty slots (null)
names[0] = "Ali";
names[1] = "Sara";
System.out.println(temps[2]);
temps[2] = 33;
System.out.println(temps[2]);
System.out.println("Length: " + temps.length);
System.out.println(names[2]);
}
}35 33 Length: 4 null
new String[3] creates an array of three elements filled with default values: null for objects, 0 for numbers and false for booleans. Accessing index 4 of a four-element array throws ArrayIndexOutOfBoundsException.
Looping Through an Array
public class Main {
public static void main(String[] args) {
double[] prices = {4.5, 12.0, 7.25};
double sum = 0;
for (int i = 0; i < prices.length; i++) {
System.out.println("Item " + i + ": " + prices[i]);
sum += prices[i];
}
System.out.println("Total: " + sum);
}
}Item 0: 4.5 Item 1: 12.0 Item 2: 7.25 Total: 23.75
The Arrays Utility Class
java.util.Arrays has ready-made methods for sorting, printing, searching, filling and copying arrays.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {42, 7, 19, 3, 25};
System.out.println(Arrays.toString(nums));
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.binarySearch(nums, 19));
int[] bigger = Arrays.copyOf(nums, 7);
System.out.println(Arrays.toString(bigger));
System.out.println(Arrays.stream(nums).max().getAsInt());
}
}[42, 7, 19, 3, 25] [3, 7, 19, 25, 42] 2 [3, 7, 19, 25, 42, 0, 0] 42
Printing an array directly with println shows something like [I@1b6d3586, a type code and hash, not the contents. Use Arrays.toString instead.
Two-Dimensional Arrays
A 2D array is an array of arrays, perfect for tables and grids. Use two indexes: [row][column].
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]);
for (int[] row : grid) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}6 1 2 3 4 5 6
Frequently asked questions
How do I find the length of an array in Java?
Use the length field without parentheses: myArray.length. Strings use a length() method, which is a common point of confusion.
Can a Java array change size?
No. Arrays have a fixed size. Create a bigger copy with Arrays.copyOf, or use an ArrayList, which grows automatically.
How do I print an array in Java?
Use Arrays.toString(array) for one-dimensional arrays and Arrays.deepToString(array) for multi-dimensional arrays.