Java Arrays
Fixed-size, ordered collection of elements of the same type.
Declaring an array
Declaration
// Empty array of size 5 int[] numbers = new int[5]; // Array initialized with values int[] primes = {2, 3, 5, 7, 11}; // String array String[] names = {"Raman", "Aman", "Priya"};
Accessing elements
Arrays are zero-indexed. The first element is at index 0.
Index access
String[] names = {"Raman", "Aman", "Priya"}; System.out.println(names[0]); // "Raman" System.out.println(names[2]); // "Priya" names[1] = "Sara"; // modify element
ArrayIndexOutOfBoundsException
Accessing
names[5] on an array of size 3 throws ArrayIndexOutOfBoundsException at runtime. Always check i < array.length.
Length
Use .length (it's a field, not a method — no parentheses):
length
int[] nums = {10, 20, 30, 40}; System.out.println(nums.length); // 4
Iterating an array
Two ways
int[] nums = {10, 20, 30}; // Classic for loop — when you need the index for (int i = 0; i < nums.length; i++) { System.out.println(i + ": " + nums[i]); } // for-each — when you only need the value for (int n : nums) { System.out.println(n); }
Default values
When you create an array with new int[5], all elements get the default for that type: 0 for numbers, false for boolean, null for objects.
Multi-dimensional arrays
An array of arrays — useful for grids, matrices, tables.
2D array
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(matrix[1][2]); // 6 (row 1, col 2) for (int[] row : matrix) { for (int v : row) { System.out.print(v + " "); } System.out.println(); }
Useful array utilities
The java.util.Arrays class has helpful static methods:
Arrays utility
import java.util.Arrays; int[] nums = {5, 2, 8, 1, 9}; Arrays.sort(nums); // {1, 2, 5, 8, 9} System.out.println(Arrays.toString(nums)); // [1, 2, 5, 8, 9] int[] copy = Arrays.copyOf(nums, 3); // {1, 2, 5} boolean equal = Arrays.equals(nums, copy);
Limitation: fixed size
Once an array is created, its size is fixed forever. To grow or shrink dynamically, use ArrayList (covered in the Collections section).