Method Arrays.toString()
The Arrays.toString() method in Java provides a convenient way to get a string representation of a one-dimensional array. Instead of manually looping through the array elements using a for
loop or for-each
loop, this method automatically formats the output with elements separated by commas and enclosed in square brackets.
This is especially useful for debugging or logging, as it quickly displays the contents of an array in a readable format.
Here is an example demonstrating how to use Arrays.toString()
:
import java.util.Arrays;
public class ArraysToStringExample {
public static void main(String[] args) {
int[] array = {1, 4, 6, 3, 8};
System.out.println(Arrays.toString(array));
}
}
Output:
[1, 4, 6, 3, 8]
Note: The Arrays.toString()
method works only for one-dimensional arrays. If you try to use it with a multidimensional array, you will get a memory reference rather than a readable string. To convert multidimensional arrays to a string, use Arrays.deepToString()
instead.
For example:
int[][] twoDArray = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(twoDArray));
Output:
[[1, 2], [3, 4]]

Please log in or register to have a possibility to add comment.