Arrays toString JAVA

Printing the string representation of the array | Arrays toString JAVA

Well, from the name of this method, we can understand that this method converts our given array into a string. This method returns the string representation of the contents in the array, as a list of array elements enclosed in square brackets. Also, the elements are separated using the comma followed by a space.

Let’s have a look at the program now –

import java.util.Arrays;
public class ArrayBasic {
public static void main(String[] args) {
int[] somearray = new int[] {1, 2, 3, 4, 5, 6, 7};
System.out.println(Arrays.toString(somearray));
}
}

If you try to execute the above program, the output comes out to be the string representation of the array, with all the elements separated by a comma followed by a space. As mentioned earlier, this method returns a string, so we can have a reference variable for this, in case you want to access it later. Have a look at the below program which explains the same thing –

import java.util.Arrays;
public class ArrayBasic {
public static void main(String[] args) {
int[] somearray = new int[] {1, 2, 3, 4, 5, 6, 7};
String arrayString = Arrays.toString(somearray);
System.out.println(arrayString);
}
}

Well, executing this program will not have any change in the output, since we are again printing the same string, just this time we are using the reference variable we created. Note that we are getting a string here.

We can use this method to print the string representation of the array as and when needed. For a few examples from now, let’s use this method to print the output of the array.