Skip to main content
Engineering LibreTexts

16.3: Displaying Arrays

  • Page ID
    15258
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    You can use println to display an array, but it probably doesn’t do what you would like. For example, the following fragment (1) declares an array variable, (2) makes it refer to an array of four elements, and (3) attempts to display the contents of the array using println:

    int[] a = {1, 2, 3, 4};
    System.out.println(a);
    

    Unfortunately, the output is something like:

    [I@bf3f7e0
    

    The bracket indicates that the value is an array, I stands for “integer”, and the rest represents the address of the array. If we want to display the elements of the array, we can do it ourselves:

    public static void printArray(int[] a) {
        System.out.print("{" + a[0]);
        for (int i = 1; i < a.length; i++) {
            System.out.print(", " + a[i]);
        }
        System.out.println("}");
    }
    

    Given the previous array, the output of this method is:

    {1, 2, 3, 4}
    

    The Java library provides a utility class java.util.Arrays that provides methods for working with arrays. One of them, toString, returns a string representation of an array. We can invoke it like this:

    System.out.println(Arrays.toString(a));
    

    And the output is:

    [1, 2, 3, 4]
    

    As usual, we have to import java.util.Arrays before we can use it. Notice that the string format is slightly different: it uses square brackets instead of curly braces. But it beats having to write the printArray method.


    This page titled 16.3: Displaying Arrays is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?