← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 8 of 10

Java Arrays Introduction

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

java
public class Main {
	public static void main(String[] args) {
		int[] numbers = new int[5];
		System.out.println(numbers.length);
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		int[] nums = {1, 2, 3};
		System.out.println(nums[1]);
	}
}

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

java
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
	}
}

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

java
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);
		}
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.