Author
Arrays are one of the most important data structures in Java. They help store multiple values of the same type efficiently and provide easy access to elements using indices.
In Java, arrays can be classified into:

A 1D array is a linear collection of elements. It’s like a list where each element is accessed by an index starting from 0.
int[] numbers; // Preferred way
int numbers2[]; // Also valid
numbers = new int[5]; // Array of size 5 (default values 0)
int[] scores = {90, 80, 70, 60, 50}; // Direct initialization
public class OneDArrayDemo {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
for(int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " + arr[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Key Points About 1D Arrays:
Multi-dimensional arrays store data in a matrix or grid format.
[row][column].int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // 6 (second row, third column)
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Output:
1 2 3
4 5 6
7 8 9
[layer][row][column].int[][][] cube = {
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};
System.out.println(cube[1][0][1]); // 6
Here, cube[1] is the second layer, cube[1][0] is the first row of that layer, and cube[1][0][1] is the second element.
int[][] jagged = new int[3][];
jagged[0] = new int[] {1, 2};
jagged[1] = new int[] {3, 4, 5};
jagged[2] = new int[] {6};
for(int i = 0; i < jagged.length; i++) {
for(int j = 0; j < jagged[i].length; j++) {
System.out.print(jagged[i][j] + " ");
}
System.out.println();
}
Output:
1 2
3 4 5
6
[row][column].[layer][row][column].ArrayList.ArrayIndexOutOfBoundsException.