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?
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:
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.
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!