How to print an Array without using Loops in Java?
Whenever the question of printing the contents of an array arises, the first solution which
comes to our mind is Loops. Do you think we can print the contents of an array without using
loops? If your answer is yes, then you are right. In this article, we are going to explore
how to print contents of an array without using loops in Java.
Let us first look at an example code which prints all the contents of an array without
using loops, and then we will talk about how it does that.
Example
Output
Let us look at the output of the above example code.
As you can see in the above code, we have used the toString method print all the
elements of
the array. The toString method is the member of the Arrays class in the
java.util package.
This method is used for String representation of the arrays.
There is an extension to this toString method which is used in
multi-dimensional array,
let us look at that.
Example
Output
Let us look at the output of the above example code.
For multi-dimensional array, we use the method deepToString.
Why are we not using the toString method here, any idea? Let us try and find
out what will
happen if we use toString method in multi-dimensional array
Output
Let us look at the output of the above example code.
What do you think these weird alpha numbers indicate? Well, these are the addresses of the elements. See! Why we don`t use toString method in multi-dimensional array.
Summary
In this article, we explored a method to print contents of an array apart from the traditional loop technique, which is, using the toString method of the Array class. For the multi-dimensional array we use the deepToString method to print all the contents of an array.