3 min read
29 Jun, 2025
Java
Arrays are one of the most fundamental data structures in Java. Whether you're just getting started with Java or preparing for coding interviews, a strong grasp of arrays is essential. In this blog post, we’ll walk through everything you need to know about arrays in Java — from basic concepts to common operations — with plenty of examples along the way.
An array in Java is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created and cannot be changed afterward.
Think of an array as a row of lockers, each holding a value, and all lockers are the same size (i.e., the same data type).
int[] numbers; // Recommended int numbers[]; // Also valid
numbers = new int[5]; // creates an array of 5 integers
int[] numbers = {10, 20, 30, 40, 50};
Note: Array indices in Java are zero-based, so the first element is at index 0
.
System.out.println(numbers[0]); // Outputs: 10 numbers[2] = 99; // Changes the third element to 99
Trying to access an index out of bounds will throw an ArrayIndexOutOfBoundsException
.
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
for (int num : numbers) { System.out.println(num); }
import java.util.Arrays; Arrays.sort(numbers);
int index = Arrays.binarySearch(numbers, 30);
int[] copy = Arrays.copyOf(numbers, numbers.length);
Arrays.fill(numbers, 100); // fills entire array with 100
Java supports multidimensional arrays, often used for matrices and grids.
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(matrix[1][2]); // Outputs: 6
Nested loops are commonly used to iterate through 2D arrays.
ArrayList
.int
, float
, double
→ 0
boolean
→ false
Object
references → null
Arrays in Java form the bedrock of many data structures and algorithms. Mastering arrays equips you with the tools to solve a wide range of problems efficiently. As you continue your journey in Java, understanding how to manipulate arrays will help you build faster, cleaner, and more effective code.
Have questions or want more practice problems? Drop a comment below — or stay tuned for the next post in this Java DSA series!