Explain Codes LogoExplain Codes Logo

How to convert an int array to String with toString method in Java

java
arrays
string-conversion
streams
Anton ShumikhinbyAnton Shumikhin·Aug 24, 2024
TLDR

To convert an int array into a string form, employ Arrays.toString() from the java.util.Arrays class. It generates a structured string containing all array elements, enclosed in brackets and discerned by commas.

Example:

// Did you ever think that an army of numbers could be trapped in a String prison? Look here: String arrayString = Arrays.toString(new int[]{1, 2, 3}); // Produces: "[1, 2, 3]"

Step-by-Step Breakdown

The Arrays.toString(int[]) method offers an absolute solution for converting an int array to a String in Java. Here's the detailed breakdown for every novice and pro coder.

Java 8 Streams for Custom Array Formatting

Streams, introduced in Java 8, cover a broad spectrum of operations, including custom formatting of an int array:

// The artist in you can paint the int array to look like a String String result = Arrays.stream(yourArray) .mapToObj(String::valueOf) .collect(Collectors.joining(", "));

Sanity Check with Null Arrays

Life isn't perfect, and neither are arrays. Sometimes, they're null. But that's no problem for the Arrays.toString() method, it spits out "null". So, you're safe from sudden NullPointersException ambushes!

Output Clean-Up Time

After a wild night out with Java, your output may need a little cleanup. Remove unneeded brackets, spaces, or commas using the magic of Regex:

// Cleaning up after the party, phase 1: take away brackets, commas and whitespaces String cleanOutput = Arrays.toString(yourArray).replaceAll("\\[|\\]|,|\\s", "");

Or keep it classy and clean from the get-go with a stream:

// Cleaning up phase 2: using a stream, Java is our mom... it cleans as it goes! String cleanOutput = Arrays.stream(yourArray) .mapToObj(String::valueOf) .collect(Collectors.joining());

Let's Dive Deeper

Conversion Details

Doing the legwork, Arrays.toString() audaciously employs String.valueOf(int), making every int a convincing String actor!

Avoid Direct toString() on Arrays

Proceed with caution! An array's own toString() will definitely not satisfy your taste buds. Stick to Arrays.toString(array) for the authentic String flavor of your array.

Back to the Numeric Reality

If your String only consists of numbers, just do a Long.parseLong(intStr) and you're back to numeric reality. Especially handy for heavy-duty number crunching.

Custom Behaviours with Stream Operations

For those brave souls seeking out coding adventures and custom manipulations of array elements during conversion, Java Streams are your best ally offering operations like filtering, mapping, and even collecting.