An Array is a foundational data structure in Java that stores a fixed-size sequential collection of elements of the exact same data type. In Java, all arrays are dynamically allocated Objects on the Heap.
Arrays use zero-based indexing, meaning the first element is at index 0 and the last element is at index length - 1:
public class ArrayDemo {
public static void main(String[] args) {
// Approach 1: Declare and allocate size (initialized to 0)
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
// Approach 2: Declare with literal initialization
String[] fruits = { "Apple", "Mango", "Banana", "Orange" };
// Reading length and accessing items:
System.out.println("Array Size: " + fruits.length); // 4
System.out.println("First Fruit: " + fruits[0]); // Apple
System.out.println("Last Fruit: " + fruits[fruits.length - 1]); // Orange
}
}
A 2D array represents data in a tabular grid of rows and columns:
int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
// Accessing element at Row 1, Column 2:
System.out.println("Element [1][2]: " + matrix[1][2]); // Output: 6
Because Java treats multidimensional arrays as "arrays of arrays", each row can hold a sub-array of differing length:
public class JaggedArrayDemo {
public static void main(String[] args) {
// Declare 2D array with 3 rows, unspecified columns
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // Row 0 has 2 columns
jagged[1] = new int[4]; // Row 1 has 4 columns
jagged[2] = new int[1]; // Row 2 has 1 column
System.out.println("Row 0 columns: " + jagged[0].length); // 2
System.out.println("Row 1 columns: " + jagged[1].length); // 4
}
}
Exam Question: "What exception is thrown if you access index arr[arr.length]?"
Answer: java.lang.ArrayIndexOutOfBoundsException! Because array indexes range strictly from 0 to length - 1, attempting to read or write at index arr.length or any negative index triggers an unchecked runtime bounds violation.
Now let us explore the built-in utility methods of the java.util.Arrays class. Proceed to: java.util.Arrays Utility Class →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Sorting, searching, and copying arrays.
Resizable dynamic array alternative.
Traversing array elements cleanly.
String[] args array.