In this post under Java Collections, I will show with example how to convert an array into its string representation.
In Java, any object when converted to its string representation, it calls the object’s “toString” method.
The default behavior of “toString” method is to print the below information
getClass().getName() + '@' + Integer.toHexString(hashCode())
In case of Array, class name is replaced by character “[” followed by single character representing the element data type.
So in case of integer array it will printed like this
[I@439f5b3d
And in case of double array, it will printed like this
[D@1d56ce6a
Usually when we call “toString” method on an array, we expect it to print the elements of the array but that is not the case as shown previously.
To achieve the desired output, “Arrays” class provides “toString” overloaded static method which will take an array and return a string containing comma separated elements sorrounded by square bracket.
As shown in the below output
[5, 2, 3, 1, 4]
Below the main class that shows how to use this overloaded static method.
Main class
package core.collection;
import java.util.Arrays;
public class ArraysToStringDemo {
public static void main(String [] args) {
int[] integerList = new int[] {5, 2, 3, 1, 4};
System.out.println(Arrays.toString(integerList));
}
}
In the above code, at line 7, I create an array of integer elements.
At line 8, I call “Arrays” “toString” method and pass the array as an argument. This method will return a string containing comma separated elements sorrounded by square brackets. Which is then printed to the console.
In this way we can obtain the string representation of an array.