How to print an array in Java

print an array in Java

An array is a type of variable that can store multiple values with an index. This allows developers to modify, arrange, and organize large data sets. Something that developers need to do often, is print an array in Java. In this post, we’ll explore how to do that.

See also: How to use arrays in Python

How to print an array in Java – the easy way

There are a few different types of array in Java and a few ways to print each of them.

The main Java Array looks like this:

String vegetables[] = {"broccoli", "cauliflower", "potato", "carrot", "spinach", "beans"};

This is an array that contains the names of different vegetables. I can print any element from that list like so:

System.out.println(vegetables[3]);

In order to print an array in its entirety, I would simply need to create a little loop.

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

That, very simply, is how to print an array in Java.

How to print other types of array

An Array List is an array that can change size at runtime. This means you can add and remove new elements.

The great news is that this type of array can be printed in its entirety with no need for a loop. It’s even easier:

import java.util.ArrayList;

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

    ArrayList<String> arrayListOfFruit = new ArrayList<String>();
    arrayListOfFruit.add("Apple");
    arrayListOfFruit.add("Orange");
    arrayListOfFruit.add("Mango");
    arrayListOfFruit.add("Banana");
    System.out.println(arrayListOfFruit);

  }

}

Of course, the same loop trick will work just as well!

A map is a type of array in Java that allows you to assign unique key/value pairs that stay the same. This way, you can create something like an address book, where each number (value) is given a contact name (key).

You can print an entire map, just like you can print an Array List:

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
  
    Map<String, String> phoneBook = new HashMap<String, String>();
    phoneBook.put("Adam", "229901239");
    phoneBook.put("Fred", "981231999");
    phoneBook.put("Dave", "123879122");
    System.out.println(phoneBook);
    

  }
}

However, you also have the option to print individual elements from the map:

System.out.println("Adam's Number: " + phoneBook.get("Adam"));

Closing comments

So, now you know how to print an array in Java!

If you want to learn more tricks of the trade, then be sure to check out our Java tutorial for beginners. Alternatively, why not get a more comprehensive education from one of our best resources to learn Java.

This entry was posted in Android Development, How To. Bookmark the permalink.