Arrays are a fundamental data structure that allow you to store a fixed number of elements of the same type in a contiguous block of memory. They’re widely used for storing data when you know the exact number of elements beforehand, and they offer a more efficient way to manage large amounts of data compared to using individual variables for each element. Here’s a breakdown of the core concepts surrounding arrays in Java:
int
, double
, char
) or a reference type (such as String
or custom objects).0
, the second element at 1
, and so on. The last element is at index array.length - 1
, where array.length
returns the total number of elements.Arrays can be declared and initialized in a few ways:
int[] numbers;
declares an array of integers.new
keyword to allocate memory for the array and specify its size: numbers = new int[5];
creates an integer array that can hold five elements.int[] numbers = new int[5];
int[] numbers = {1, 2, 3, 4, 5};
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements by index
System.out.println("First element: " + numbers[0]);
System.out.println("Second element: " + numbers[1]);
// Modify an element
numbers[2] = 10;
System.out.println("Updated third element: " + numbers[2]);
// Loop through an array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}