Arrays are the essential computational component to store any kind of sequential information. In this section, we study the details of how to create and process arrays to the best of their use with Java.
Array basics
Exercise: Maximum of array elements
Write a Java application which can return the maximum element in a given array of integers. In your program, assume the user is asked to enter an arbitrary number of integers. Example input: { 1, 8, 3, 5, 12, 4, 2 } Example output: “The maximum value is 12.”
Solution
A straightforward method for finding a given element in the array is to perform linear search, where we iterate through each element and compare its value to fulfill a desired condition. In this case, we can use an intermediate variable which, starting from the first element, continuously stores the current maximum in the array, and returns the last saved value which was the largest element.
Exercise: Alphabet with Array
Write a Java program that stores all letters in the English alphabet in a character array, in the sorted order.
Solution
In this example, we can use the special property of the ASCII table, which encodes the hexadecimal representation of each letter in the alphabet in the sorted order. Starting from the letter ‘a’, a for loop will increment the value representing each letter, and store their values in a character array.
Elementary array operations
The elementary operations for processing arrays, such as copying, inserting, deleting or swapping elements in an array are some of the most frequently used methods in implementing data structures. Try to implement for yourself each operation to gain more practical experience.
Searching and sorting
Searching and sorting are commonly used operations in many algorithms in computer science. It’s going to be very useful to know at least one way to implement searching and sorting arrays in Java.
Multi-dimensional arrays
Exercise: Weather forecast
You are given a table full of data on weather information in New York, distributed across the time of the year. Write a Java method that finds the month with the maximum amount of humidity, the total amount of rain over the whole year and the average temperature over the whole year.
Solution
We first start by saving the weather data in a 2-dimensional array for easily represent the modular information. In order to compute the maximum amount of humidity, we can then iterate through the last column, storing the humidity values, and compute the maximum. To find out which month the corresponding index refers to, we could store the month names in a String array with the same number of rows.
In order to implement the second part of the exercise, we can now iterate over the second first column, and sum all rain values stored each month.
We can also compute the average temperature over the whole year by summing the values in the second column corresponding to temperature, and divide the sum by the number of months.