2) Data Structures Lesson

Java Array

11 min to complete · By Jon Fincher

In Java, arrays are the first basic data structure you learn about right after learning about variables. You can define exactly what you mean by an array.

What is an Array

In Java, an array is a collection of values of the same data type. You access data value in an array using an index, which is an integer value that uniquely identifies each item in the array. In Java, indexes start with 0 -- that is, the first item in the array is at index 0.

Why use an Array

Arrays are used to store and access related data in a specific order. Because the index is an integer, an order is implicitly imposed on array data. You can say things like "the first item in the array", "the twelfth item in the array," or "the last item in the array".

Because of this, arrays are great for storing sequential data, which can be ordered in some way.

Examples of an Array

To illustrate these points, take a look at a small example. You can say you want to track the high temperatures measured in our location for a week. You might use something like this:

int[] highTemps = new int[7];

As with all Java variables, you preface the name of the variable highTemps with its type. In this case, the syntax int[] specifies that this is an array that will hold int data. After the declaration, you define how many data values are held in the array with the syntax new int[7].

Colorful illustration of a light bulb

You are using new here, which indicates that arrays in Java are an object type, not a primitive type like int or double.

You can store our high temperatures for the week using the following code:

highTemps[0] = 65;
highTemps[1] = 67;
highTemps[2] = 70;
highTemps[3] = 68;
highTemps[4] = 71;
highTemps[5] = 63;
highTemps[6] = 63;

Each index appears within the square brackets ([]) and can be used to either retrieve or set the value at that index.

You can also update any value in the array at any time:

highTemps[3] = 72;

You can also initialize an array when it is declared:

int[] highTemps = {65, 67, 70, 68, 71, 63, 63};

This code declares highTemps as an array and defines the length and values it contains in a single line.

Benefits of using an Array

Of course, you can declare and use a set of individual variables to store the same data:

int highTemp0 = 65;
int highTemp1 = 67;
int highTemp2 = 70;
int highTemp3 = 68;
int highTemp4 = 71;
int highTemp5 = 63;
int highTemp6 = 63;

However, what if you wanted to find the highest high temperature for the week using these variables? You would have to compare each one to a known value to find the highest:

int highest = highTemp0;
if (highTemp1 > highest){
  highest = highTemp1;
}
if (highTemp2 > highest){
  highest = highTemp2;
}
if (highTemp3 > highest){
  highest = highTemp3;
}
if (highTemp4 > highest){
  highest = highTemp4;
}
if (highTemp5 > highest){
  highest = highTemp5;
}
if (highTemp6 > highest){
  highest = highTemp6;
}

Using the array, this is done very easily with a for loop:

int highest = highTemps[0];
for (int i=0; i<highTemps.len; i++){
  if (highTemps[i] > highest){
    highest = highTemps[i];
  }
}

This code works even if highTemps is a different size -- maybe you're tracking a month or a year of high temperatures.

In fact, the ability to use loops to work with arrays is one of the biggest benefits. Adding, removing, and processing values in an array is greatly simplified with loops.

Use Cases of an Array

You can take a look at a practical use case for an array. Our simple example has been tracking high temperatures, but what if you wanted to track a range of weather-related data over the course of a month and output some analysis?

First, create a POJO to hold onto the data you want to track:

public class DailyWeatherData{
  // Track high and low temperatures
  private int highTemp;
  private int lowTemp;

  // Total rainfall in inches
  private double rainfall;

  // Humidity as a percentage
  private double humidity;

  // Barometric pressure
  private double pressure;

  // Wind speed and direction in degrees
  private int windSpeed;
  private int windDirection;

  // Add constructor, getters, and setters here

}

You can add the constructor, getters, and setters as well to complete the POJO. An array is used to store the data and to gather the data you need; you can use a loop and a Scanner to get data from the user:

public class WeatherTracker{

  public static void main(String[] args){
    // Store one month's worth of data here
    DailyWeatherData[] weatherData = new DailyWeatherData[30];

    // Create a scanner to get user input
    Scanner scanner = new Scanner(System.in);

    for (int i=0; i<weatherData.length; i++){
      // Create an object to store the data
      DailyWeatherData 
        singleDayWeatherData = new DailyWeatherData();

      System.out.println("Enter weather data for day #" + i);
      System.out.println("------------------------------");

      System.out.print("High temperature: ");
      singleDayWeatherData.highTemp = scanner.nextInt();

      System.out.print("Low temperature: ");
      singleDayWeatherData.lowTemp = scanner.nextInt();

      System.out.print("Rainfall in inches: ");
      singleDayWeatherData.rainfall = scanner.nextDouble();

      System.out.print("Humidity from 0.0 - 1.0: ");
      singleDayWeatherData.humidity = scanner.nextDouble();

      System.out.print("Barometric pressure: ");
      singleDayWeatherData.pressure = scanner.nextDouble();

      System.out.print("Wind Speed: ");
      singleDayWeatherData.windSpeed = scanner.nextInt();

      System.out.print("Wind Direction in degrees: ");
      singleDayWeatherData.windDirection = scanner.nextInt();

      // Store the data in the array
      weatherData[i] = singleDayWeatherData
    }
  }
}

Of course, you could also read the daily weather data from a file or download it from a web API. However you get your data, you can perform analysis on it using loops. For example:

public static void analyzeWeatherData(DailyWeatherData[] weatherData){
  // You need to store the total for everything
  int totalHighTemp=0;
  int totalLowTemp=0;
  int totalWindSpeed=0;

  double totalRainfall=0.0;
  double totalHumidity=0.0;
  double totalPressure=0.0;

  // Add everything up
  for (int i=0; i<weatherData.length; i++){
    totalHighTemp  += weatherData[i].highTemp;
    totalLowTemp   += weatherData[i].lowTemp;
    totalRainfall  += weatherData[i].rainfall;
    totalHumidity  += weatherData[i].humidity;
    totalPressure  += weatherData[i].pressure;
    totalWindSpeed += weatherData[i].windSpeed;
  }

  // Output some averages
  System.out.println("Average High      : " 
    + (totalHighTemp / weatherData.length));
  System.out.println("Average Low       : " 
    + (totalLowTemp / weatherData.length));
  System.out.println("Average Rainfall  : " 
    + (totalRainfall / weatherData.length));
  System.out.println("Average Humidity  : " 
    + (totalHumidity / weatherData.length));
  System.out.println("Average Pressure  : " 
    + (totalPressure / weatherData.length));
  System.out.println("Average Wind Speed: " 
    + (totalWindSpeed / weatherData.length));

}

Exercise

Modify the code above to read data from the weatherData.csv file, which contains high and low temperatures, rainfall, humidity, pressure, wind speed, and wind direction data for a given 30-day period. Then, output the following:

  • Average temperatures, pressure, rainfall, humidity, and wind speed over that period.
  • Maximum high and low temperatures, minimum high and low temperatures.
  • Highest daily rainfall.
  • Highest and lowest wind speeds.
  • Most common wind direction.

Summary: Arrays

The array is the most basic data structure, storing a collection of values of the same data type and referenced by an index. Array indexes start at 0, and all arrays have a defined length that is unchangeable over the life of the array. Loops work extremely well with arrays to add, retrieve, and operate on data in the array.