Appearance
How to convert an int array to String with toString method in Java
To convert an int array to a string in Java, you can use the Arrays.toString() method from the java.util package. The toString() method converts an array to a string representation in the form [elem1, elem2, ..., elemN].
Here is an example of how you can use the toString() method to convert an int array to a string:
java
import java.util.Arrays;
int[] array = {1, 2, 3, 4, 5};
String str = Arrays.toString(array); // str is now "[1, 2, 3, 4, 5]"In this example, the toString() method is used to convert the array int array to a string representation. For multi-dimensional arrays, use Arrays.deepToString() instead.
You can also use the String.join() method to convert an int array to a string, separating the elements with a delimiter. Note that Arrays.toString() is generally preferred for standard comma-separated output.
For example:
java
import java.util.Arrays;
int[] array = {1, 2, 3, 4, 5};
String str = String.join(", ", Arrays.stream(array).mapToObj(String::valueOf).toArray(String[]::new)); // str is now "1, 2, 3, 4, 5"This code converts the array int array to a stream of strings, using the mapToObj() and String::valueOf methods. The stream is then converted back to an array of strings using the toArray() method, and the String.join() method is used to concatenate the elements of the array with the delimiter ", ".