How to print Array content as String in Java?

Viewed 938

How can the Array content be converted to a String in Java?

Example:

int[] myArray = {1,2,3};

The output has to be:

"123"

Arrays.toString(myArray) is returning:

"[1, 2, 3]"

and myArray.toString(), returns:

[I@12a3a380

So none of them works. Is there a function for this?

This question might look similar to (this), but is actually different. I am literally asking for a String made of all the array entries.

4 Answers
String joined = Arrays.stream(myArray)
            .mapToObj(String::valueOf)
            .collect(Collectors.joining(""));

System.out.println(joined);   

The old-fashioned way:

StringBuilder builder = new StringBuilder();
for (int value : myArray) {
  builder.append(value);
}
... now use builder.toString()

Less fancy compared to the stream solution, but on the other hand: in case runtime performance matters, this here should beat any other approach.

A curveball approach is to remove any non-digit character from the ouput of one of the traditional serialization methods:

Arrays.toString(myArray).replaceAll("\\D", "");

which yields 123 in your example.

replaceAll replaces all positive matches of the regular expression in the first parameter with the contents of the second parameter. \D is regex for anything that is not a digit.

I will go old school, which works every time no matter what as follows:

String myString = "";
for(int val : myArray)
{
  myString += val;
}

System.out.println(myString); // To check the output of myString

Will work! Hope this helps!

Note: This will work in Embedded Java as well where StringBuilder and some other classes are stripped for embedded devices.

Related