[!NOTE] Often, you'll need to store a list of related data—like 50 high scores or 10 usernames. Instead of creating 50 separate integer variables, you can store them in a single Array.
Declaring and Initializing Arrays
An Array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is strictly fixed.
// Method 1: Literal Initialization (when you know the values upfront)
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myScores = {10, 20, 30, 40};
// Method 2: Size Initialization (when you just want to reserve space)
int[] blankArray = new int[5]; // Creates space for 5 integers, all defaulting to 0
Accessing Elements
You access an array element by referring to the index number. Array indexes start with 0. [0] is the first element, [1] is the second, etc.
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars[0]); // Outputs "Volvo"
// Modifying an element
cars[0] = "Opel";
System.out.println(cars[0]); // Now Outputs "Opel"
[!CAUTION] If you create an array of size 3, and try to access
cars[3], you will get a catastrophicArrayIndexOutOfBoundsException. Remember, a size 3 array only has indexes0, 1, 2.
Looping Through Arrays
To iterate over every element in an array, you have two amazing options.
Standard For Loop
Use this if you need to know the exact index you are currently processing.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println("Car at index " + i + " is: " + cars[i]);
}
The Enhanced For-Each Loop
Introduced in Java 5, this loop cleanly iterates through the elements without you having to manage an index counter.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}