Today we are going to discuss the simplest way to print the array as a string in Java: Arrays.toString() method.
How to use Arrays.toString() method?
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Returns “null” if a is null.
In case of an Object Array, if the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
- public static String toString(boolean arr)
- public static String toString(byte arr)
- public static String toString(char arr)
- public static String toString(double arr)
- public static String toString(float arr)
- public static String toString(int arr)
- public static String toString(long arr)
- public static String toString(Object arr)
- public static String toString(short arr)
arr – the array whose string representation to return
the string representation of arr
The below mentioned Java code depicts the usage of the toString() method of Arrays class with examples:
[true, true, false, true] [10, 20, 30] [g, e, e, k, s] [1.0, 2.0, 3.0, 4.0] [1.0, 2.0, 3.0, 4.0] [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
We can also use Arrays.toString() for objects of user defined class.
Since Arrays.toString() is overloaded for array of Object class (there exist a method Arrays.toString(Object )) and Object is ancestor of all classes, we can use call it for an array of any type of object.
[111 bbbb london, 131 aaaa nyc, 121 cccc jaipur]
Why does Object.toString() not work for Arrays?
Using the toString() method on Arrays might not work. It considers an array as a typical object and returns default string, i.e., a ‘[‘ representing an array, followed by a character representing the primitive data type of array followed by an Identity Hex Code [See this for details]
This article is contributed by Shikhar Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.