Home >Java >javaTutorial >Why Does `System.out.println()` Print a Strange Output When Displaying a Java Array, and How Can I Correctly Print Its Elements?

Why Does `System.out.println()` Print a Strange Output When Displaying a Java Array, and How Can I Correctly Print Its Elements?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 04:14:09356browse

Why Does `System.out.println()` Print a Strange Output When Displaying a Java Array, and How Can I Correctly Print Its Elements?

Arrays in Java: Unraveling Mysterious Output and Printing Array Elements

Java arrays provide a convenient way to store and manipulate collections of elements of the same type. However, when printing an array using System.out.println(), you may encounter unexpected output.

Consider the following code snippet:

int[] arr = new int[5];

arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;

System.out.println(arr);

When executed, this code will produce output similar to "[I@3e25a5". This output represents the object's class name ("[I") followed by the array's address in memory ("3e25a5").

To display the actual elements of the array, you can use either of the following techniques:

  1. Java.util.Arrays.toString():

    System.out.println(java.util.Arrays.toString(arr));

    This utility method returns a string representation of the array, enclosing the elements within square brackets.

  2. Looping Through the Array:

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

    This loop iterates through the array, printing each element on a separate line.

By utilizing these techniques, you can obtain the desired output, representing the exact numbers from the array.

The above is the detailed content of Why Does `System.out.println()` Print a Strange Output When Displaying a Java Array, and How Can I Correctly Print Its Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn