Back in the days when I first learned arrays in the Java programming language, I was very impressed with the visualization of arrays on the internet like the following example...
..so I want such array visualization to appear in my output to make it easier for me to debug if something goes wrong in my program.
Can you guess what I did?
Yes, I'm trying to print the object array as you can see in Source code 1.
Source code 1:
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr);
Which will produce the following output...
Output 1:
[I@24d46ca6
Then I realized that if we try to print an object in Java, the memory location of the object will be printed.
Then I thought, I have to implement the code for my own array visualization to be able to achieve the result I want.
Therefore, I decided to implement the code as you can see in Source code 2.
Source code 2:
int[] arr = {1, 2, 3, 4, 5};
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if(i == arr.length-1)
System.out.print(arr[i]);
else
System.out.print(arr[i] + ", ");
}
System.out.println("]");
It was a success, because my code was able to print the array as I wanted it to look like in Output 2.
Output 2:
[1, 2, 3, 4, 5]
After reading the documentation for the Arrays
class in Java, I know that there is one method that can be used to print an array. The method is .toString()
, and it takes one parameter as you can see in Syntax 1.
Syntax 1:
public static String toString(int[] a)
-
a
is the array.
Source code 3 is the implementation of this method.
Source code 3:
int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
And with far fewer lines of code, the implementation of this method has the same result as Source code 2.
Output 3:
[1, 2, 3, 4, 5]
So, if you are trying to print an array with a good look, you can use the toString()
method which comes from the Arrays
class. And also a note, although in this article I use array of integers as the example, but this method can also take arguments with various datatypes such as short
, boolean
, etc.
Cover image:
https://i.picsum.photos/id/354/1920/720.jpg?hmac=WuwPQPiZ87_tIKjOq3jreJ3EtT-b-Mn4HpETLfusBv4
Other image:
https://www.kirupa.com/html5/images/shuffled_200.png
Top comments (0)