Array in Java: store multiple values in a single variable


Keywords: array, one-dimensional array, multidimensional array, arraylist

Array Java programming

In this chapter, we will learn how to use Array and ArrayList in Java to store and structure data. We will see what Array and ArrayList are and how we can create and work with them by solving several examples. Additionally, we will also introduce and look at the for-each loop and hashtable in this chapter.

Array in Java

An array in Java is used to store multiple values in a single variable, instead of declaring separate variables for each value. In other words, an array is a collection of elements stored in what can be described as a list. Each element in an array consists of the same data type and can be retrieved and used with its index.

We will see how we can use so-called one-dimensional arrays, described as a list of elements and the so-called multidimensional array that resembles a table or a matrix. Additionally, we will also take a closer look at the array list, as the name suggests, is closely related to an array and gives us the possibility to work with sets of data that are changing in size.

This chapter includes the following articles:

  • To be updated

What is an Array in Java?

We saw earlier that we could imagine a variable in Java as a box that can store value of a certain data type. The variable is also given a name.

Array Variable Java Programming

Figure 1: Variable in Java

Similarly, we can now think of an array as a box with several boxes inside.

Array Java Programming

Figure 2: Array in Java

Furthermore, we will see how we can access each box using its index, that is, the element’s position in an array. Therefore, we can use the value, read it, and even edit it. It is important to note that indexing always starts at 0; that is, the first value gets index 0, the second value gets index 1, and so on.

An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use non-negative integer index values. All the components of an array have the same type, called the component type of the array.

Oracle

How to create array in Java?

We could describe it as that there are generally two approaches to creating an array in Java. We have chosen to call them approach one and approach two. Before we start, remember that all values in an array must be of the same data type. For example, you cannot save a double in an array created for the data typeint.

Syntax: Declaring array in Java with approach one

// Declaring array with approach one
data type [] name = new data type [number of elements];

Let’s look at the code above

  • We start by specifying the array’s data type, followed by a square brackets [ ] and the name of the array
  • Then we use the equal sign = and the reserved word new
  • Finally, we enter the same data type that we have chosen to work with followed by the number of elements we want to create in square brackets [], and then finish with a semicolon;

Example: Declare an array with approach one

Let’s take a short example to illustrate what it looks like when using what we call approach one to create an array. First, we start by creating an array that contains no values.

// Example declaring array with approach one
int[] arrEx = new int [4];

Since we did not initialise a starting value for our array elements, they have all been automatically assigned the value 0.

Example Array Java Programming

Figure 3: Example of an array in Java

Moreover, we want to save values in arrEx, and to do that; we can use the index for each element.

arrEx[0] = 22; 
arrEx[1] = 8;  
arrEx[2] = 97;  
arrEx[3] = 3;

Finally, resulting in

Exercise Array Java Programming

Figure 4: Example of an array in Java

Syntax: Declaring array in Java with approach two

Instead of creating the array with new and then saving values in each element, we can directly assign values to the array element when declaring it. We declare the array by

// Declaring array with approach two
data type [] name = { value, value, value, value, … } ;

Note that in this case, it is curly brackets { } that are used to the right of the equals sign.

Example: Declare an array with approach two

If we want to create the array that we used in approach one, the one we named arrEx, we code:

// Example declaring array with approach two
int[] arrEx = {22, 8, 97, 3};

That will result in the same array as before

Exercise Array Java Programming

Figure 5: Example of an array in Java

Finally, we can use, read and edit each element in the array using indexes in the same way as in approach one.

Default values when declaring array in Java

As we saw in the example for approach one, if we don’t declare a value when we create an array, Java will assign the element a so-called default value. The default value for the different data types is:

Data type                              Default value
byte, short, int, long             0
float, double                         0.0
boolean                                false
object                              null

How to select approach to create array in Java?

A good rule of thumb, which may seem obvious, is to:

  • If the array does not have initialised values or many elements that do not have initialised values, then approach one is preferred.
  • On the other hand, an array where each element has a starting value, approach two is more straightforward and faster to use.

Our recommendations, if you feel unsure about arrays and how they are structured and declared, it may be easier to use approach one. It may take a little bit longer to declare and is more detailed, but it can also help you understand how the array is structured. Additionally, if you are unsure how the array looks, it might help to use a piece of paper and draw the boxes with indexes and their assigned values.

Example: Array in Java

Let’s have a look at an example of how to use an array in Java. In addition to using an array, we will also use a method that we learned in the previous chapter. What we want the program to do is to:

  • Create an array that contains five names that we choose randomly
  • Then the program should ask the user to enter an integer between 0-4. Here we assume that the user enters the correct type of data.
  • Finally, take the integer that the user entered and print the name stored at that index in the array we created.

To help us, we will create a method that takes an array and an integer as arguments, and then prints the name stored on the index entered by the user.

// Imports the Scanner class
import java.util.Scanner;

public class Example {

    // Method that takes an array with string and a int as arguments
    public static void printName (String [] inArr, int userInput) {

        System.out.println("Name on index: " + userInput +
                " is: " + inArr[userInput]);

    }

    public static void main(String args[]) {  
        // Our array of names
        String [] arrEx = {"Charles", "Sara", "Matt", "Anna", "Sofie"};

        // Declare scanner objects to save input
        Scanner in = new Scanner(System.in);

        System.out.println("Enter integers between 0-4 to " +
                "print a name");

        // Saves the integer the user enters
        int userInput = in.nextInt();

        // Calls the method
        printName(arrEx, userInput);
    }
}

Finally, this was the first example of using an array in Java to store and use data. In the following articles, we will see several different examples of how we can work with an array.

Why use array in Java?

As you probably already have realised, an array will be advantageous when we develop our programs as we will often handle extensive collections of data. Thus, an array is useful to be able to structure and group these values. Instead of creating individual variables for every variable we want to save, we can instead save all the data points we want within an array.

Summary: Array in Java

An array in Java is used to store multiple values in a single variable, instead of declaring separate variables for each value. Therefore, an array is a collection of fixed elements in what can be seen as a list. Each element in an array consists of the same data type and can be retrieved and used using its index. Furthermore, we can create an array with what we describe as two approaches.

Approach one for declaring an Array in Java

// Declaring array with approach one
data type [] name = new data type [number of elements];

Approach two for declaring an Array in Java

// Declaring array with approach two
data type [] name = { value, value, value, value, … } ;

FAQ: Array in Java

What happens if I don’t declare an initial value for the elements in my array?

If we don’t declare a value when we create an array, Java will assign the element a so-called default value. The default value for the different data types is:
Data type                            default value
byte, short, int, long            0
float, double                        0.0
boolean                               false
object                              null

Can you change the size of an array after you have declared it?

No, you cannot resize the array after you have created it. However, there are other (as we look at soon) data structures that can change size after creation.

Can you enter a negative number as an index in the array?

No, you cannot enter a negative number as the array index. If you enter a negative number as an index, you will get a compilation error.