Convert int array to String in Java example shows how to convert int array to String in Java using the Arrays class or StringBuffer/StringBuilder class.
How to convert int array to String in Java?
1) Convert int array to String using the Arrays class
We can use the toString
method of the Arrays class which accepts int array and returns a string representation of its elements as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; public class IntArrayToStringExample { public static void main(String[] args) { int[] intArray = {1, 2, 3, 4, 5}; /* * to convert int array to String use * toString method of Arrays class */ String str = Arrays.toString(intArray); System.out.println(str); } } |
Output
1 |
[1, 2, 3, 4, 5] |
All int values are wrapped in square brackets and are separated by a comma followed by a space. If you want to remove the square brackets from the string, use below given regular expression pattern along with the replaceAll method of the String class.
1 2 3 4 5 |
int[] intArray = {1, 2, 3, 4, 5}; String str = Arrays.toString(intArray).replaceAll("\\[|\\]", ""); System.out.println(str); |
Output
1 |
1, 2, 3, 4, 5 |
If you want to remove space and comma as well, use below given regular expression pattern.
1 2 3 4 5 |
int[] intArray = {1, 2, 3, 4, 5}; String str = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", ""); System.out.println(str); |
Output
1 |
12345 |
You can also use the “[^0-9]” pattern to remove square brackets, spaces, and comma from the output. The “[^0-9]” pattern means “not digit”, so when it is used along with the replaceAll
method, it replaces all the non-digit characters with an empty string, thus giving us only the int values.
2) Using the StringBuilder or StringBuffer class
The StringBuilder class can be used to convert int array to string as given below. We will iterate through int array and append each element of an array to the StringBuilder object. Finally, we will convert the StringBuilder object to String object using the toString
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; public class IntArrayToStringExample { public static void main(String[] args) { int[] intArray = {1, 2, 3, 4, 5}; StringBuilder sb = new StringBuilder(); //iterate through int array for(int i : intArray) sb.append(i).append(","); String str = sb.toString(); System.out.println(str); } } |
Output
1 |
1,2,3,4,5, |
Note: If you are using Java 1.4 or below version, use the StringBuffer instead of the StringBuilder class. However, it is suggested to use the StringBuilder class if you do not need multithreaded synchronization.
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below.