Use arrays in Java

Instead of tracking dozens of individual variables, use an array in Java to collect and store data in a structured way.
No readers like this yet.
What is your favorite open source Java IDE?

Pixabay. CC0.

In the Java programming language, an array is an ordered collection of data. You can use an array to store information in a structured way. It's useful to know the various ways you can retrieve that data when you need it. It's worth noting that in Java, an associative array (also called a dictionary in some languages) is called a hashmap. This article doesn't cover hashmaps, but you can read all about them in my Using a hashmap in Java article.

Creating a string array

The simplest array in Java is a one-dimensional array. It's essentially a list. For an array of strings:

package com.opensource.example;

public class Example {

    public static void main(String[] args) {
        String[] myArray = {"foo", "bar", "baz"};

        // retrieval
        System.out.println(myArray[0]);
        System.out.println(myArray[1]);
        System.out.println(myArray[2]);
    }
}

Notice that when you retrieve the data from an array, the index starts at 0, not 1. In other words, an array containing three values is numbered 0 to 2.

Alternatively, you can create an array and populate it later. When you do this, however, you must also tell Java the length of the array. The "length", in this context, refers to the number of items an array can hold.

package com.opensource.example;

public class Example {
    public static void main(String[] args) {
        String[] myArray = new String[3];

        System.out.println("Empty myArray created.");

        // populate the array
        myArray[0] = "foo";
        myArray[1] = "bar";
        myArray[2] = "baz";

        // retrieval
        System.out.println(myArray[0]);
        System.out.println(myArray[1]);
        System.out.println(myArray[2]);
    }
}

Assuming the code is saved in a file called main.java, run it using the java command:

$ java ./main.java
foo
bar
baz

To create an array of integers, define the data type as int instead of String:

package com.opensource.example;

public class Example {
    public static void main(String[] args) {
      int[] myArray = { 1, 2, 3 };

      System.out.println(myArray[0]);
      System.out.println(myArray[1]);
      System.out.println(myArray[2]);
    }
}

Run the code:

$ java ./main.java
1
2
3

Iterating over an array

Once you've stored data in an array, you probably intend to retrieve it at some point. The most direct way to see all data in an array is to create a for loop that gets the length of the array using the .length method, and then loops over the array a number of times equal to the length:

package com.opensource.example;

public class Example {
    public static void main(String[] args) {

        String[] myArray = { "foo", "bar", "baz" };

        for (int i=0; i < myArray.length; i++) {
            System.out.println(myArray[i]);
        }
    }
}

Run the code:

$ java ./main.java
foo
bar
baz

Multidimensional arrays

An array doesn't have to be just a simple list. It can also be a list of lists. This is called a multidimensional array, and it's pretty intuitive as long as you think of it as an array of arrays:

package com.opensource.example;

public class Example {
    public static void main(String[] args) {
        String[][] myArray = {{ "zombie", "apocalypse" }, { "happy", "halloween" }};
        }
    }
}

To see the contents of the array, you can use a nested for loop. In a one-dimensional array, you had to obtain the length of myArray so your for loop knew when to stop iterating over the array. This time, you must obtain the length of each array within myArray. For simplicity, I call these two arrays outer and inner, with the former being myArray, and the inner representing each nested array:

int outer = myArray.length;
int inner = myArray[1].length;

Once you have both lengths, you use them as the limits of your for loop:

for (int i = 0; i < outer; i++) {
  for (int j = 0; j < inner; j++) {
    System.out.println(myArray[i][j]);
    }
  }

Here's the full code sample:

package com.opensource.example;

  public class Example {
      String[][] myArray = {{ "foo", "bar" }, { "baz", "qux" }};

      int outer = myArray.length;
      int inner = myArray[1].length;

      for (int i = 0; i < outer; i++) {
         for (int j = 0; j < inner; j++) {
            System.out.println(myArray[i][j]);
            }
        }
    }
}

Run the code:

$ java ./main.java
zombie
apocalypse
happy
halloween

Arrays of data

Sometimes it makes more sense to use a Java array than to track dozens of individual variables. Once you understand how to structure and retrieve data in a language, you can generate complex data in an organized and convenient way.

Seth Kenlon
Seth Kenlon is a UNIX geek, free culture advocate, independent multimedia artist, and D&D nerd. He has worked in the film and computing industry, often at the same time.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.