Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you can
place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array
You can access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Loop Through an Array
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 following example outputs all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
Real-Life Example
To demonstrate a practical example of using arrays, let's create a program that calculates the
average of different ages:
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
// Get the length of the array
int length = ages.length;
// Loop through the elements of the array
for (int age : ages) {
sum += age;
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
System.out.println("The average age is: " + avg);
Example
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// Get the length of the array
int length = ages.length;
// Create a 'lowest age' variable and assign the first array element of ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (int age : ages) {
// Check if the current age is smaller than the current 'lowest age'
if (lowestAge > age) {
// If the smaller age is found, update 'lowest age' with that element
lowestAge = age;
// Output the value of the lowest age
System.out.println("The lowest age in the array is: " + lowestAge);