What are Arrays? 

The simplest way to start thinking about an array is as a collection, or a set of elements. In programming, these elements may be constants, variables, functions and pointers. 

What’s special about the elements that make up an array is: 

  • They form a sequence. 
  • They all are of the same data type. 
  • They all are identified by a single name. Each element is marked by an index, as the numbers in a mathematical sequence are marked by subscripts. 
  • The index of an element marks its place in the sequence. 

Formally, an array is a data structure used to store elements sequentially. A data structure is an organized collection of data values, together with the relationships that exist between the values, and the operations that can be performed on the values. 

The sequential elements of an array are referred to, and accessed, by a number called the index. In Java, the first element of an array has the index 0, the second element has the index 1, and so forth. 

To illustrate, imagine you have five variables of the same data type—say the “char” data type—as in this collection: 

"Five individual variables of the same data type"

Let’s also say you’re using these variables to store the number of hours you worked each day of a week, from Monday through Friday. The value of “m” might be 7.0, the value of “t” might be 6.5, and so forth. 

Given this, it would make more sense to use one variable—perhaps an integer variable called “HoursWorked”—to store your data. The value of “HoursWorked” for the first day of the week would then be 7.0, the value for the second day of the week would be 6.5, and so forth. 

Now imagine organizing your data this way: 

"Organizing individual variables of the same data type as an array"

All the elements in the sequence HoursWorked1, HoursWorked2, and so on have the same name but different suffixes, are of a floating point data type, and are differentiated in terms of their place in the sequence “HoursWorked.” 

As you’ve probably guessed, “Hours Worked” is an array. 

Why Arrays are Useful? 

In the example you just saw, it might have been all right to use five variables rather than an array. But what if you needed to store the names of 100 students in a school? Across programming languages, using an array called “StudentNames” would be easier than using 100 variables called “StudentName1,” “StudentName2,” and so on. 

Using an array is a much more elegant, efficient way of storing certain kinds of data—such as the number of hours worked each day of a week—compared with the use of individual variables. If you worked longer the next week by one hour a day, you could represent the data for the next week using a similar array—which would require just one additional variable (perhaps an array called “HoursWorked2”). You’d be able to change the values from those of the previous week using one statement rather than five. 

Elegance and efficiency apart, there are several compelling reasons to use an array rather than individual, independent variables. We can use arrays to: 

  • Simplify the assignment of values of variables. 
  • Make it easy to access variables and fetch their values. 
  • Simplify operations such as sorting a set of variables that represent similar or related data. 
  • Reduce the amount of coding when the same operation is to be performed on a set of values. 

Using Arrays in Programming

Say you want to store the highest temperatures, in degrees Fahrenheit, recorded in a city for every day of a year—from January 01 through December 31, in sequence. You’d use an array for this purpose. Let’s call the array “HighTemp.” 

Temperatures have decimal points, so each value would be of a floating point data type. The collection of values in an array needs to be of the same data type, which would also be the data type of the array. 

So, the array “HighTemp” could be of any of the floating-point data types—for example, double in Java. 

  • As you might expect, the data values in an array are stored in contiguous memory locations. The index 0 corresponds to the first element, which in turn corresponds to the first—and lowest—memory location address. 
  • The index 364 corresponds to the last element, which in turn corresponds to the last—and highest—memory location address. 
  • You’d refer to, and access, the temperature corresponding to the nth day of the year using the index n-1, as in “HighTemp[n-1].” That is, the index of the nth memory location is n-1. 
  • The temperature recorded for February 04, which is the 35th day of the year, is stored in the location HighTemp[34]. 

Defining and Initializing Arrays 

You’re familiar with the process of assigning values to individual variables, which includes defining the variable and assigning a value of the correct data type to the variable. Assigning values to the elements of an array is similar. 

Let’s look at several ways to define and/or initialize an array that is called MyArray, is of the integer data type, and will contain three values: 14, 15, and 16. 

1. You can declare and initialize a Java array at the same time using this statement: 

int[ ] MyArray = {14, 15, 16}; 

Here, 

  • “int” specifies the data type of an array with the name “MyArray.” 
  • The values within the braces are the values assigned to the elements of MyArray. 

You define a JavaScript array either by just using square brackets or by specifying the data structure called "Array." So both the following work in JavaScript:  

  •        var MyArray = [14, 15, 16] 
  •        var MyArray = [14, 15, 16] 

While there's no general rule across languages for declaring and initializing arrays, it's almost universally true that an array variable needs to be indicated as such. 

2. You could define the array, and then initialize the value of each element in the array using separate statements: 

int[] MyArray = new int[3]; // this defines the array  

MyArray[0] = 14; // this initializes the first element of the array  

MyArray[1] = 15; // this initializes the second element  

MyArray[2] = 16; // this initializes the third element 

3. If needed, you can define the size of the array using a variable—and the syntax doesn’t change: 

int a = 3; 

int[] MyArray = new int[a]; 

Remember that you can’t leave the size of an array unspecified or undefined. In cases where you might need an array to have an undefined size that gets fixed depending on, say, user input, you’d use a list (an ArrayList in Java) rather than an array. 

For the same reason, while it is often desirable to do so, you can’t just insert a value at the end of an array without knowing its size. You’d need to first determine the size of the array using a property called “length,” and then insert the element at the end of the array using the position indicated by the length property. So if you wanted to insert “19” as the last element of MyArray as above, without knowing the size of the array, you’d use the length property, whose syntax is as in the code below: 

int lengthOfMyArray = MyArray[].length; 

MyArray[lengthOfMyArray - 1] = 19; 

To prepend an element to the beginning of an array, however, you’d have to use a list—specifically, an ArrayList—rather than an array, and use the “unshift” function. The unshift function moves all the elements in a list up by one position. 

4. Remember that you don’t need to initialize all the elements of the array at once. Here’s a piece of Java code that defines MyArray as above, and only initializes the second value: 

int[] MyArray = new int[3]; 

MyArray[1] = 15; //This initializes the second element of MyArray as 15 

It might appear in the examples above that MyArray is an array. Actually, The variable “MyArray” is only a reference to an array. So, for example, if you were to say: 

int[] MyNewArray = MyArray; 

You wouldn’t be copying the contents of MyArray into something called MyNewArray. You’d only have two variables, MyArray and MyNewArray, each of which is a reference to the same array. 

Accessing the Elements of an Array 

As mentioned, the elements of an array are accessed by a number called the index. To assign the value of the second element in MyArray to an integer variable called SecondElement—and see the output—you would use this code segment: 

int SecondElement = MyArray[1]; 

System.out.println("The second element of MyArray is " + SecondElement + "."); 

Output: The second element of MyArray is 15. 

Multi-Dimensional Arrays 

A multi-dimensional array is, in simple terms, an array of arrays. If an array is like a row, a multi-dimensional array is like a table of rows and columns. 

Let’s go back to the number of hours you worked each day for five days in a week: 

Say you want something more complete than just this sequence of values: a table that holds the day numbers, as well as the hours, worked on each day. You can create such a table using a two-dimensional array: 

"Organizing sets of correlated variables as a two-dimensional array"

In general, a multi-dimensional array can have any number of dimensions. 

Our example above has data in two “dimensions,” which creates a simple table. The length—or size—of the first dimension is 2. This allows for the two categories of “day number” and “hours worked.” The size of the second dimension, which allows for the data to be assigned, is 5. 

Remember that the elements of an array need to be of the same data type. In this example, the number of hours worked—such as “6.5”—needs to be represented by variables of a floating-point type. So, the day numbers—such as “1” and “2”—also need to be of a floating-point type. Their values will be “1.0,” “2.0,” and so forth. 

Putting it all Together

Let’s now look at a Java program that creates a two-dimensional array—a table that stores the first five numbers along the top row, with their squares computed and stored along the bottom row. We want the code to output the first five squares. 

public class Main { 

public static void main (String[] args) { 

int[][] SquaresOfNumbers = new int[2][5]; 

// This defines SquaresOfNumbers as an array of two integer arrays—or, a two-dimensional integer array that represents a 5x2 table. 

int i, j; 

int[] theNumbers = new int[5]; // This defines theNumbers as an array that holds five integers  

int[] theSquares = new int[5]; // This defines theSquares as an array that holds five integers 

for (i = 0; i < 5; i++) { 

theNumbers[i] = i + 1; // This sets the integers in the array theNumbers to the numbers 1 through 5  

System.out.print("The array called theNumbers holds these numbers: "); 

for (i = 0; i < 5; i++) { 

System.out.print(theNumbers[i] + " "); 

System.out.println(); 

for (i = 0; i < 5; i++) { 

theSquares[i] = theNumbers[i] * theNumbers[i]; 

// This sets the integers in the array theSquares to the squares of the integers in the array theNumbers  

System.out.print("The array called theSquares holds these numbers: "); 

for (i = 0; i < 5; i++) { 

System.out.print(theSquares[i] + " "); 

System.out.println(); 

for (i = 0; i < 5; i++) { 

SquaresOfNumbers[0][i] = theNumbers[i]; 

// This sets the values in the top row of the two-dimensional array SquaresOfNumbers to the values in the array theNumbers 

SquaresOfNumbers[1][i] = theSquares[i]; 

// This sets the values of the bottom row of the two-dimensional array SquaresOfNumbers to the values in the array theSquares 

for (i = 0; i < 5; i++ ) { 

System.out.println ("The square of " + (i+1) + " is " + SquaresOfNumbers[1][i] + "."); 

Output: 

The array called theNumbers holds these numbers: 1 2 3 4 5 

The array called theSquares holds these numbers: 1 4 9 16 25 

The square of 1 is 1. 

The square of 2 is 4. 

The square of 3 is 9. 

The square of 4 is 16. 

The square of 5 is 25. 

Common Mistakes

Here are a few errors you’re likely to make when beginning to code arrays in Java.

1. The first index of an array is 0, not 1.

After defining an array, say an integer array as “int[] MyNewArray = MyArray”, it’s easy to mistakenly write MyArray[1] intending to refer to the first element in MyArray. Remember that the indexes of an array begin from 0.

2. Be careful in the for loops.

When you write a for loop in a Java program to access the elements of an array, pay attention to how you initialize and end the counter. If MyArray is an integer array with five elements, you might use the following to print them out:

for (i = 0; i <= 5; i++) {
System.out.println(MyArray[i]);
}

This code, which will try to access the nonexistent MyArray[5], will throw an ArrayIndexOutOfBoundsException. Just as the first index is 0, the last index has a value equal to one less than the length of the array.

3. Remember what happens when you create a reference to an array.

As you saw, when you use the following two lines:

int[] MyArray = new int[3];
int[] MyNewArray = MyArray;

MyArray and MyNewArray both become references to the same array. A change in the former will be reflected in the latter, and vice versa.

Suppose MyArray holds the numbers 10, 20, and 30, and you set MyNewArray to be “equal” to MyArray as above. Say you later perform an operation on MyNewArray so the values are doubled, and MyNewArray holds 20, 40, and 60. What would you expect the following line to print?

System.out.println("The second element of MyArray is " + MyArray[1] + ".");

It’s easy to imagine this would output 20, but it outputs 40 because “MyArray” and “MyNewArray” are just two names, or aliases, for the same array.

Context and Applications

This topic is significant in the professional exams for both undergraduate and graduate courses, especially for

  • Bachelors in Technology (Computer Science)
  • Masters in Technology (Computer Science)
  • Bachelors in Science (Computer Science)
  • Masters in Science (Computer Science)



Want more help with your computer science homework?

We've got you covered with step-by-step solutions to millions of textbook problems, subject matter experts on standby 24/7 when you're stumped, and more.
Check out a sample computer science Q&A solution here!

*Response times may vary by subject and question complexity. Median response time is 34 minutes for paid subscribers and may be longer for promotional offers.

Search. Solve. Succeed!

Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.

Tagged in
EngineeringComputer Science

Programming

Introduction to Coding

Array

Array Homework Questions from Fellow Students

Browse our recently answered Array homework questions.

Search. Solve. Succeed!

Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.

Tagged in
EngineeringComputer Science

Programming

Introduction to Coding

Array