Arrays are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets [].
You can initialize an array by providing the values in a comma-separated list inside curly braces {}.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]); // Outputs Volvo
}
}
Alternatively, you can declare an array and allocate memory for it using the new keyword, and then assign values to it.
String[] fruits = new String[3]; fruits[0] = "Apple"; fruits[1] = "Banana"; fruits[2] = "Orange"; System.out.println(fruits[1]); // Outputs Banana
You access an array element by referring to its index number. Array indexes start at 0.
To change the value of a specific element, refer to the index number and use the assignment operator.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford"};
// Access the second element
System.out.println(cars[1]); // Outputs BMW
// Change the first element
cars[0] = "Opel";
System.out.println(cars[0]); // Outputs Opel
}
}
To find out how many elements an array has, use the length property (note that it's not a method, so no parentheses).
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length); // Outputs 4
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
The for-each loop is an even easier way to iterate through an array.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Using a for-each loop
for (String car : cars) {
System.out.println(car);
}
}
}