Arrays allow you to store multiple values of the same data type in a single variable. They are one of the most important data structures in Java.
1. What is an Array?
An array groups related values so you can access them using an index. The index always starts from 0.
Try example:
public class ArrayBasicDemo {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println("First car: " + cars[0]); // Output: Volvo
System.out.println("Total cars: " + cars.length);
}
} 2. Single-Dimensional Arrays
1D arrays store values in a single list.
Try example:
public class SingleArrayDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
System.out.println("Before change: " + numbers[0]);
numbers[0] = 50; // Modify value
System.out.println("After change: " + numbers[0]);
}
} 3. Array Operations
A. Looping with Index
Try example:
public class ArrayLoopDemo {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
} B. Enhanced For-Each Loop
Try example:
public class ArrayForEachDemo {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
System.out.println(car);
}
}
} 4. Multi-Dimensional Arrays
Multi-dimensional arrays store values in a grid (rows & columns).
Try example:
public class TwoDArrayDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println("Value at row 1, col 2: " + matrix[1][2]); // Output: 6
}
} Traversing a 2D Array
Try example:
public class TwoDArrayLoopDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}