Java Arrays
Explains how to declare and use arrays in a Java program.
Prerequisites
- Understand Java primitive types
- Understand execution flow and the following Java control structures:
- Sequence
- Selection (if and switch statements)
- Repetition (while, for, and do while statements)
Objectives
- Understand the importance and practical uses of arrays
- Learn how to declare, create, and initialize an array
- Understand how an index in an array works
- Use a
forloop with an array - Understand multi-dimenstional arrays
- Become familiar with common
Arraylibrary functions
When to Use an Array
- Arrays are an important and useful tool in most programming languages.
- An array can be loosely defined as a collection of variables.
- Instead of writing code to work with many variables of the same type, you can write code to work with an array which holds many variables.
- Each variable in an array is called an element.
- Some cases in which an array would be useful are:
- You need to write a program that averages the test scores of 100 students. Instead of declaring and using 100 variables, you can store 100 values in an array.
- You need to temporarily store many names in a program. Instead of declaring many
Stringvariables, you can store them in a single array of Strings.
Declaring an Array
- Before using any variable, including an array, in a Java program, you must declare that variable.
- Syntax:
dataType[] arrayName; - Examples:
int[] testScores; double[] dailyTemps; float[] accountBalances;
Creating an Array
- Declaring an array in Java does not cause the computer to reserve space for the elements of that array.
- You must use the
newkeyword to create the array. - Syntax:
arrayName = new dataType[arraySize]; - Examples:
double[] empSalaries; // array declaration empSalaries = new double[6]; // array creation int dataLength = 15; int[] data; // array declaration data = new int[dataLength]; // array creation
Initializing the Values in an Array
- It is possible to both declare and create an array on a single line.
- Syntax:
dataType[] arrayName = new dataType[arraySize]; - Examples:
double[] empSalaries = new double[6]; int dataLength = 15; int[] data = new int[dataLength]; - In an array created as shown in the previous example, each element will automatically be initialized to 0, null, or false depending on the data type.
- It is possible to declare, create, and populate the values in an array on one line of code.Syntax:
dataType[] arrayName = { value0, value1, … };Examples:String[] employees = { "Bob", "Larry", "Ben", "Louise" }; double[] sizes = { 13.8, 22.1, 18.6, 18.5, 17.4 };Array Length
- All Java arrays have an attribute named
lengthwhich is the number of elements contained in the array. - Syntax:
arrayName.length - Example:
String[] array = { "Ben", "Emily", "Albert", "Lydia" }; int len = array.length; // len will hold 4 - Arrays in Java have a fixed length, or in other words the length of an array in a Java program cannot change while that program is running.
Array Indexes
- Every variable in an array, called an element, has an index or location.
- The first index of a Java array is always 0.
- The last index of a Java array is always the length of the array minus 1.
- You can store or retrieve individual values in an array by using the index.
- Examples:
// Create an array that stores double floating point numbers. double[] sizes = { 13.8, 22.1, 18.6, 18.5, 17.4 }; // 13.8 is stored at index 0 (the first index). // 17.4 is stored at index 4 (the last index). // Change the value at index 2 from 18.6 to 15.9 sizes[2] = 15.9; // Add the values at indexes 3 and 1. double result = sizes[3] + sizes[1]; - Trying to access an element before the first or beyond the last index of an array causes an ArrayIndexOutOfBoundsException.
double[] sizes = { 13.8, 22.1, 18.6, 18.5, 17.4 }; sizes[-1] = 14.1; // Causes an ArrayIndexOutOfBoundsException sizes[5] = 15.0; // Causes an ArrayIndexOutOfBoundsException
Arrays and the For Loop
- When working with arrays, you will often use a for loop.
- Examples:
// Printing the contents of an array: String[] empNames = { "Heath", "Garth", "Chandra", "Susan" }; for (int i = 0; i < empNames.length; i++) { System.out.println(empNames[i]); } // Finding the largest element in an array: double[] hourlyWage = { 7.75, 8.00, 9.00, 8.50 }; double max = hourlyWage[0]; for (int j = 1; j < hourlyWage.length; j++) { if (hourlyWage[j] > max) { max = hourlyWage[j]; } }
Multidimensional Arrays
- Arrays can hold any data type, including other arrays.
- A multidimensional array is simply an array of arrays.
- Examples:
// Create an empty array with 4 rows and 6 columns. double[][] matrix = new double[3][6]; // Create an array with three rows and three columns. char[][] ticTacToe = { {'x', 'o', 'x'}, {'o', 'x', 'o'}, {'o', 'o', 'x'} }; - An array can have as many dimensions as you want. However, multidimensional arrays often use lots of memory. Consider the following three dimensional array named
world. Even though each dimension is relatively small (50, 200, and 200), the entire array uses 2,000,000 bytes (2 megabytes) of memory.double[][][] world = double[50][200][200]; // 8 bytes * 50 * 200 * 200 = 2,000,000 bytes
Library Functions
- The standard Java class
java.util.Arrayscontains many useful methods for manipulating arrays, including the following:asListbinarySearchcopyOfequalsfillsorttoString
Arraysclass. - Examples:
import java.io.PrintStream; import java.util.Arrays; public class TestLibFuncs { public static void main(String[] args) { // Make a local variable that enables shorter syntax for // printing to the console. PrintStream out = System.out; // Create an array that contains four vegetable names. String[] vegies = { "radish", "carrot", "tomato", "pea" }; out.println("vegies " + Arrays.toString(vegies)); // Create a copy of the vegies array and show that the // contents of the original and the copy are the same. String[] copy = Arrays.copyOf(vegies, vegies.length); out.println("copy " + Arrays.toString(copy)); out.println("equal? " + Arrays.equals(vegies, copy)); out.println(); // In the original array, replace "tomato" with "pepper" // and show that the original array changed but the copy // didn't change. vegies[2] = "pepper"; out.println("vegies " + Arrays.toString(vegies)); out.println("copy " + Arrays.toString(copy)); out.println("equal? " + Arrays.equals(vegies, copy)); out.println(); // Fill the entire copy array with "potato". Arrays.fill(copy, "potato"); out.println("copy " + Arrays.toString(copy)); out.println(); // Sort the vegies array and show that its contents are // in sorted order. Arrays.sort(vegies); out.println("vegies " + Arrays.toString(vegies)); // Find the index where "pea" is stored in the sorted array. int index = Arrays.binarySearch(vegies, "pea") out.println("location of pea? " + index); // Attempt to find the index where "okra" is stored in // the sorted array. Because "okra" is not in the array, // the binarySearch method will return a negative integer. index = Arrays.binarySearch(vegies, "okra") out.println("location of okra? " + index); if (index < 0) { // Use the negative integer to determine where okra // should be stored in the sorted array. index = -index - 1; out.println("okra should be stored at " + index); } } }vegies [radish, carrot, tomato, pea] copy [radish, carrot, tomato, pea] equal? true vegies [radish, carrot, pepper, pea] copy [radish, carrot, tomato, pea] equal? false copy [potato, potato, potato, potato] sorted [carrot, pea, radish, tomato] location of pea? 1 location of okra? -2 okra should be stored at 1
Further Reading
You can learn much more about arrays from chapter 1 of Advanced Programming Techniques.