Arrays are ordered collections in which we can store different values. Using them, we can maintain a well-structured and optimized code base. Arrays are one of the most frequently used data structures in Java. They provide us with a straightforward syntax that’s easy to understand even for beginners and can be put into action in many different use cases.

Arrays in Java

Although we can find arrays in most modern programming languages, Java arrays have some unique features.

Java arrays are zero-based; the first element always has the index of 0. All items in a Java array need to be of the same type, for instance, an array can’t hold an integer and a string at the same time. Java arrays also have a fixed size, as they can’t change their size at runtime. Therefore, we need to define how many elements it will hold before we initialize it.

To initialize an array in Java, we need to follow these five simple steps:

  1. Choose the data type
  2. Declare the array
  3. Instantiate the array
  4. Initialize values
  5. Test the array

In the narrow sense, initialization means that we specify (initialize) a value for each index (0, 1, 2, etc.) in the array. This is Step 4 in the above list, however, we have to perform all the other steps if we want our array to work properly.

1. Choose the Data Type

As I mentioned before, we can only store elements of the same data type in a Java array. Arrays can store primitive data types (integers, floats, characters, booleans) or objects such as strings. Most frequently, arrays hold either numeric values or strings. However, it’s also possible to create arrays of other kinds of objects, as this tutorial by JavaWithUs excellently explains it. As arrays themselves constitute a separate data type in Java, arrays can hold other arrays as well. These arrays are called multi-dimensional arrays.

2. Declare the Array

If we know which data type we want to use, declaration of an array is easy. In case of primitive data types, we use the following syntax:

int[] myIntArray;

or

int myIntArray[];

Both syntaxes are valid, but the first one is more frequently used. The most important thing not to forget is the presence of the square brackets that tell the Java compiler the new variable will be an array.

In case of objects, the syntax is similar, but we need to capitalize the object type, for instance String is written with a capital S:

String[] myStringArray;

or

String myStringArray[];

3. Instantiate the Array

Now, we need to create a new instance of the chosen data type using the new keyword. Plus, we also need to define the size of the array in order to allocate memory for its items.

The following line instantiates an integer array with five items:

int[] myIntArray = new int[5];

We can instantiate a string array with five elements with a very similar syntax:

String[] myStringArray = new String[5];

It can happen that we don’t know in advance how many items our array will hold. For resizable arrays, Java provides us with the ArrayList class. If you are interested here’s a good tutorial on how to use the ArrayList class.

At this point, the Java compiler already validates our code. Both arrays are empty, however already hold five null elements of their own data type. After compiling the code, we will find the following output in the console:

// Console output

myIntArray: [0, 0, 0, 0, 0]

myStringArray: [null, null, null, null, null]

4. Initialize Values

Now, we need to fill up our arrays, or with other words initialize it. If the array is not very large we can initialize the values one by one, using the assignment operator (equals sign):

myIntArray[0] = 21;

myIntArray[1] = 27;

myIntArray[2] = 33;

myIntArray[3] = 38;

myIntArray[4] = 42;

and

myStringArray[0] = “New York City”;

myStringArray[1] = “Chicago”;

myStringArray[2] = “Los Angeles”;

myStringArray[3] = “Philadelphia”;

myStringArray[4] = “Seattle”;

If we run the code now we can see that our two arrays are initialized (they don’t have null elements anymore):

// Console output

myIntArray: [21, 27, 33, 38, 42]

myStringArray: [New York City, Chicago, Los Angeles, Philadelphia, Seattle]

If we work with a bigger array it’s also possible to initialize all values at once, using the following syntax:

myIntArray = new int[] {21, 27, 33, 38, 42};

and

myStringArray = new String[] {“New York City”, “Chicago”, “Los Angeles”, “Philadelphia”, “Seattle”};

As Java is a versatile language, there are also other ways to initialize an array. For instance, we can use for loops or get the values from user input. JavaDevNotes has a good article on specific initialization techniques; if you are interested further in the subject have a quick look.

If we want to be super efficient, we can also use a shorthand for the whole initialization process. Which means we can declare, instantiate, and initialize an array at the same time (Step 2 – Step 4). We can do that in one of two ways:

int[] myIntArray = {21, 27, 33, 38, 42};

String[] myStringArray = {“New York City”, “Chicago”, “Los Angeles”, “Philadelphia”, “Seattle”};

or

int[] myIntArray = new int[] {21, 27, 33, 38, 42};

String[] myStringArray = new String[] {“New York City”, “Chicago”, “Los Angeles”, “Philadelphia”, “Seattle”};

5. Test the Array

Now, our arrays are initialized, however we may also want to test them if they really work properly. To do so, we need to convert the arrays to strings using Java’s Arrays.toString()method, then print them out on the screen. We also need to import the java.utils.Arrays class in order to have access to Java’s pre-built array methods.

The following code outputs the values of myIntArray and myStringArray in the console which shows that our arrays have been properly initialized.

import java.util.Arrays;

public class ExampleArrays {

      public static void main(String[] args) {
          int[] myIntArray = new int[] {21, 27, 33, 38, 42};
          System.out.println(“myNewIntArray: ” + Arrays.toString(myIntArray));

          String[] myStringArray = new String[] {“New York City”, “Chicago”, “Los Angeles”, “Philadelphia”, “Seattle”};
          System.out.println(“myStringArray: ” + Arrays.toString(myStringArray));
       }

}

The final output in Eclipse:

Products You May Be Interested In:

About Cynthia Lopez

Cynthia is the managing editor and a frequent contributor at Watchdog Reviews. She's been writing about tech-focused topics and trends since 2014.

Leave a Reply

Your email address will not be published. Required fields are marked *