Java Arrays
1D Arrays
An array is a fixed-size, ordered collection of elements of the same type. Array indices start at 0.
public class Arrays1D {
public static void main(String[] args) {
// Declaration and allocation
int[] scores = new int[5]; // default values: 0
// Initialization
scores[0] = 90;
scores[1] = 85;
scores[2] = 78;
scores[3] = 92;
scores[4] = 88;
// Array literal (declare + initialize at once)
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
// Access elements
System.out.println("First score: " + scores[0]); // 90
System.out.println("Last fruit: " + fruits[fruits.length - 1]); // Date
// Iterate with for-each
int sum = 0;
for (int s : scores) {
sum += s;
}
System.out.println("Average: " + (sum / scores.length)); // 86
}
}
2D Arrays (Matrices)
A 2D array is an array of arrays — think of it as a table with rows and columns.
public class Arrays2D {
public static void main(String[] args) {
// 2D array (3 rows, 3 columns)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access element at row 1, column 2
System.out.println(matrix[1][2]); // 6
// Print entire matrix
for (int[] row : matrix) {
for (int val : row) {
System.out.printf("%3d", val);
}
System.out.println();
}
// Jagged array — rows have different lengths
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{2, 3};
jagged[2] = new int[]{4, 5, 6};
for (int[] row : jagged) {
for (int v : row) System.out.print(v + " ");
System.out.println();
}
}
}
Arrays Utility Class
java.util.Arrays provides static helper methods for common array operations.
import java.util.Arrays;
public class ArraysUtil {
public static void main(String[] args) {
int[] nums = {5, 2, 8, 1, 9, 3};
// sort — ascending order
Arrays.sort(nums);
System.out.println(Arrays.toString(nums)); // [1, 2, 3, 5, 8, 9]
// binarySearch — array must be sorted first
int idx = Arrays.binarySearch(nums, 8);
System.out.println("Index of 8: " + idx); // 4
// fill — set all elements to a value
int[] filled = new int[5];
Arrays.fill(filled, 7);
System.out.println(Arrays.toString(filled)); // [7, 7, 7, 7, 7]
// copyOf — copy with new length
int[] copy = Arrays.copyOf(nums, 4);
System.out.println(Arrays.toString(copy)); // [1, 2, 3, 5]
// copyOfRange — copy a slice
int[] slice = Arrays.copyOfRange(nums, 2, 5);
System.out.println(Arrays.toString(slice)); // [3, 5, 8]
// equals — compare two arrays
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, b)); // true
}
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.