We cannot print array elements directly in Java, you need to use Arrays.toString() or Arrays.deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.
In Java, arrays do not overwrite toString(). When we try write array directly to output console in Java, we get class_name + ‘@’ + hash_code of the array define by Object.toString(). See the below example for a better understanding.
Thus, to print Java array in a meaningful way, you don’t need to look further because your very own Collection framework provides lots of array utility methods in java.util.Arrays class. Here we have toString() method and deepToString() method to print array in Java.
Following are the methods to write an array of strings to the output console.
Method 1: Using Arrays.toString()
This method is used when you have one dimensional array.
[Geeks, for, Geeks]
Above, we have used the Arrays.toString() method. Simply pass array name as argument in Arrays.toString() and all the elements of the array will get written in the output console.
Method 2: Using Arrays.deepToString()
This method is used when you have to two dimensional array.
[[GeeksforGeeks, Article Writing], [Google, Search Engine], [Facebook, Social Media]]
In the above example, we have used Arrays.deepToString() method. This method takes care of writing elements of two dimensional array to output console.
Method 3: Using for loop
In this method, we will access each element of the array and would write it to the output console.
Geeks for Geeks
In the above method, we have used for loop() method to access every element of gfg array and write it to the output console.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.