Creating and Using Arrays
Arrays store multiple values of the same type in a fixed-size container.
Example
// Declare and initialize
int[] numbers = {10, 20, 30, 40, 50};
String[] names = new String[3]; // empty array of size 3
// Access elements (0-indexed)
System.out.println(numbers[0]); // 10
numbers[2] = 99; // modify element
// Array length
System.out.println(numbers.length); // 5
// Loop through array
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// For-each loop
for (int num : numbers) {
System.out.println(num);
} Multi-dimensional Arrays and Arrays Class
Java supports multi-dimensional arrays and provides the Arrays utility class for common operations.
Example
import java.util.Arrays;
// 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // 6
// Arrays utility methods
int[] arr = {5, 3, 1, 4, 2};
Arrays.sort(arr); // [1, 2, 3, 4, 5]
String str = Arrays.toString(arr); // "[1, 2, 3, 4, 5]"
int idx = Arrays.binarySearch(arr, 3); // 2
int[] copy = Arrays.copyOf(arr, 3); // [1, 2, 3]
Arrays.fill(arr, 0); // [0, 0, 0, 0, 0] 