Open-source News

Use arrays in Java

opensource.com - Thu, 11/24/2022 - 16:00
Use arrays in Java Seth Kenlon Thu, 11/24/2022 - 03:00

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

More on Java What is enterprise Java programming? An open source alternative to Oracle JDK Java cheat sheet Red Hat build of OpenJDK Free online course: Developing cloud-native applications with microservices Fresh Java articles 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
bazMultidimensional 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
halloweenArrays 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.

Instead of tracking dozens of individual variables, use an array in Java to collect and store data in a structured way.

Image by:

Pixabay. CC0.

Programming Java What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

Rust-Written Redox OS 0.8 Released With i686 Support, Audio & Multi-Display Working

Phoronix - Thu, 11/24/2022 - 06:53
After more than a half-year of development work, Redox OS 0.8 released today as the newest version of this from-scratch, Rust-written open-source operating system...

Intel Mesa Driver Changes Land For Building On Non-x86 CPUs

Phoronix - Thu, 11/24/2022 - 04:00
A patch was merged today to Mesa 23.0 as part of the effort for building the Intel OpenGL and Vulkan Linux drivers for non-x86/x86_64 architectures. This is part of the ongoing effort to enable Intel discrete GPUs to eventually work on the likes of AArch64, POWER, and RISC-V systems...

Pages