Java Arrays Introduction
In this page:
Declaring and Creating Arrays
An array is a fixed-size, ordered collection of elements that all share the same declared type, and its size is locked in at the moment it's created — unlike an ArrayList, you can't grow or shrink it afterward. This fixed size is what makes array access extremely fast: the JVM can compute any element's memory offset directly from its index.
Example: Declaring and Creating Arrays
public class Main {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println(numbers.length);
}
}
Login to try C/C++/Java/PHP code in the editor
Initializing Arrays
Array literals let you declare, allocate, and populate an array in one line, e.g. int[] nums = {1, 2, 3};, which is far more concise than creating the array and assigning each index separately. This shorthand only works at the point of declaration, not in a later assignment.
Example: Initializing Arrays
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(nums[1]);
}
}
Login to try C/C++/Java/PHP code in the editor
Accessing Array Elements
Array indices start at 0, so an array of length 5 has valid indices 0 through 4; asking for index 5 (or any negative index) throws an ArrayIndexOutOfBoundsException at runtime rather than failing to compile. This off-by-one mistake is one of the most common bugs beginners hit with arrays.
Example: Accessing Array Elements
public class Main {
public static void main(String[] args) {
int[] nums = {10, 20, 30, 40, 50};
System.out.println(nums[0]);
System.out.println(nums[4]);
// nums[5] would throw ArrayIndexOutOfBoundsException
}
}
Login to try C/C++/Java/PHP code in the editor
Iterating over Arrays
A standard for loop gives you the index if you need it (say, to compare neighboring elements), while an enhanced for-each loop is simpler and safer when you just need each value in turn without tracking position. For-each also avoids the possibility of an off-by-one indexing bug entirely.
Example: Iterating over Arrays
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
for (int n : nums) {
System.out.println(n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Array Properties
The length field (not a method — no parentheses) tells you how many elements an array holds, which you'll use constantly in loop bounds. Java also provides Arrays.copyOf() and System.arraycopy() for duplicating or resizing array contents into a new array object.
Example: Array Properties
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(nums.length);
int[] copy = Arrays.copyOf(nums, 3);
System.out.println(copy[0]);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: