Java Arrays: Efficiently Storing Multiple Values in a Single Variable

Learn about Java arrays, a powerful data structure used to store multiple values within a single variable. Discover how to declare an array by defining the variable type with square brackets, making your Java code more efficient and organized.


Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Declaring an Array

To declare an array, define the variable type with square brackets:

Example

String[] cars;
        

To insert values, place them in a comma-separated list inside curly braces:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
        

To create an array of integers:

Example

int[] myNum = {10, 20, 30, 40};
        

Accessing Array Elements

Access an array element by referring to the index number. Array indexes start with 0:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]); // Outputs Volvo
        
Output

Volvo
        

Changing an Array Element

To change the value of a specific element, refer to the index number:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]); // Now outputs Opel
        
Output

Opel
        

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
        
Output

4
        

Java Arrays - Real-Life Examples

Calculate Average Age

This example calculates the average of different ages using an array:

Example

// 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);
Output

The average age is: 40.75

Find the Lowest Age

This example finds the lowest age among different ages using an array:

Example

// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg

// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

// 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);
Output

The lowest age in the array is: 18