Title: Convert Between Array and String in Java
Understanding the Problem
In this guide, you will learn how to convert a Java array into a String and back again, a conversion that comes up constantly in real projects: writing log lines, exporting CSV rows, building a SQL IN clause, or preparing data to send over a network all start with turning an array into one piece of text.
Let’s explore both directions, array to string and string to array, using a delimiter you control, plus the pitfalls that catch most beginners off guard, such as regex-special delimiters and stray whitespace left behind after splitting.
Approach to Convert Between Array and String
Before writing any code, it helps to break the conversion into a small, repeatable sequence of steps that works for any array type.
- Pick a delimiter that will not appear inside the array’s own values, such as
"-"or",". - To build a
Stringfrom an array, loop through the elements and append each one to aStringBuilder. - Only prepend the delimiter before elements after the first, so the final string never starts or ends with it.
- To rebuild an array from a
String, callsplit(delimiter)to break the text back into tokens. - Escape the delimiter with
Pattern.quote()before passing it tosplit(), sincesplit()treats its argument as a regular expression. - Trim each token to remove accidental whitespace, then parse it into the target type with a method like
Integer.parseInt. - Guard against an empty input string before splitting, since splitting an empty
Stringstill produces an array containing one empty token.
Java Program
import java.util.Arrays;
public class ArrayStringConversion {
public static String arrayToString(int[] numbers, String delimiter) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numbers.length; i++) {
if (i > 0) {
sb.append(delimiter);
}
sb.append(numbers[i]);
}
return sb.toString();
}
public static int[] stringToArray(String text, String delimiter) {
if (text.isEmpty()) {
return new int[0];
}
String[] tokens = text.split(delimiter);
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i].trim());
}
return numbers;
}
public static void main(String[] args) {
int[] numbers = {7, 2, 9, 4, 1};
String joined = arrayToString(numbers, "-");
System.out.println("Array to String: " + joined);
int[] restored = stringToArray(joined, "-");
System.out.println("String to Array: " + Arrays.toString(restored));
}
}Explanation of the Program
The arrayToString method walks the numbers array once with a single for loop and accumulates the result inside a StringBuilder instead of concatenating String objects directly, since repeated String concatenation allocates a brand new object on every iteration.
The condition if (i > 0) is the entire trick behind avoiding a leading or trailing delimiter: the first element is appended on its own, and every element after it is preceded by the delimiter.
The stringToArray method reverses the process. It first guards against an empty text argument, then calls String.split(delimiter) to break the text into tokens, trims each token, and parses it into an int with Integer.parseInt.
The main method demonstrates a full round trip: an int[] is converted into a dash-delimited String, printed, converted back into an int[], and printed again with Arrays.toString so you can visually confirm the two arrays match.
Step-by-Step Trace
For arrayToString on the array {7, 2, 9, 4, 1} with delimiter "-", the target output is "7-2-9-4-1".
| Iteration | numbers[i] | Is first element? | sb (before) | sb (after) |
|---|---|---|---|---|
| 1 | 7 | yes | “” | “7” |
| 2 | 2 | no | “7” | “7-2” |
| 3 | 9 | no | “7-2” | “7-2-9” |
| 4 | 4 | no | “7-2-9” | “7-2-9-4” |
| 5 | 1 | no | “7-2-9-4” | “7-2-9-4-1” |
At the end of iteration i, sb holds the delimiter-joined string of numbers[0..i].
Examples
The examples below use fresh inputs so you can practice the same conversion pattern beyond the dry run above.
Example 1: String Array to CSV and Back
String[] names = {"Alice", "Bob", "Charlie"};
String csv = String.join(",", names);
System.out.println(csv);
// Output: Alice,Bob,Charlie
String[] restoredNames = csv.split(",");
System.out.println(Arrays.toString(restoredNames));
// Output: [Alice, Bob, Charlie]Example 2: Integer Array With a Custom Delimiter
int[] scores = {85, 92, 78};
String joined = arrayToString(scores, " | ");
System.out.println(joined);
// Output: 85 | 92 | 78
int[] restoredScores = stringToArray(joined, "\|");
System.out.println(Arrays.toString(restoredScores));
// Output: [85, 92, 78]Example 3: Arrays.toString() Is for Display, Not Round-Tripping
int[] data = {3, 6, 9};
System.out.println(Arrays.toString(data));
// Output: [3, 6, 9]
// Arrays.toString() is meant for printing. Splitting this output on
// "," would leave brackets and spaces attached to the first and last
// tokens, so it cannot be parsed back into numbers without extra cleanup.Arrays.toString() is convenient for debugging output, but its square brackets and comma-space formatting make the result unsuitable for splitting back into values. Build your own delimiter-joined string whenever you need a round trip.
Common Mistakes to Avoid
These are the mistakes that most often turn a working conversion into a runtime exception or a silently wrong array.
- Appending the delimiter after every element – including the last one produces a trailing delimiter like
"7-2-9-4-1-", which creates an extra empty token when you split it back. Only prepend the delimiter before elements after the first. - Forgetting to trim tokens after splitting – leftover whitespace such as
" 2"makesInteger.parseIntthrow aNumberFormatException. Call.trim()on every token before parsing it. - Relying on Arrays.toString() for round-tripping – its bracketed, comma-space format is meant for printing, not parsing. Build the joined string yourself with a
StringBuilderorString.joininstead. - Passing a regex-special delimiter straight into split() – characters like
"."or"|"change meaning inside a regular expression, sosplit(".")silently splits on every character. Escape the delimiter withPattern.quote()or pick a non-special character. - Using a different delimiter to join and to split – mismatched delimiters leave the entire string as one unsplit token. Define the delimiter once as a shared constant and reuse it in both directions.
Additional Considerations
Both conversions run in O(n) time and use O(n) extra space, where n is the number of elements: arrayToString makes one pass to build the StringBuilder, and stringToArray makes one pass to split and one pass to parse.
Because String is immutable in Java, every call to split() allocates a brand new array of substrings. For very large arrays, prefer a single StringBuilder over repeated + concatenation, and avoid calling split() inside a loop.
Edge Cases to Test
Walk through these inputs before calling the conversion complete.
- Empty array
- Single-element array
- Empty string converted back to an array
- String with a leading or trailing delimiter
- Consecutive delimiters producing empty tokens
- Elements that contain the delimiter character itself
- Delimiter that is a regex metacharacter (
.,|,*) - Null array or null string reference
Interview Follow-up Questions
Once the base conversion is solid, expect an interviewer to push further with questions like these.
- What if elements can contain the delimiter character? – escape or quote each value before joining, the way CSV files quote fields that contain a comma.
- What if you need to convert a 2D array instead of a 1D array? – join each row into its own string first, then join the rows together with a second, different delimiter.
- What if the array arrives as a stream of unknown length and cannot fit in memory at once? – write each converted token straight to an output stream as it arrives instead of building one giant
String, and parse the reverse direction token by token with aScannerorBufferedReader. - What if the conversion must avoid extra allocations because memory is tightly bounded? – reuse a single
StringBuilderacross calls and avoid regex-basedsplit()in favor of manually scanning the string’s characters for the delimiter.
Conclusion
Converting between an array and a String comes down to one disciplined loop in each direction: join elements with a chosen delimiter, then split and trim them back apart. Once you internalize the delimiter rules and the regex pitfalls inside split(), the same pattern adapts to any element type.
Try adapting arrayToString and stringToArray to work with double values or custom objects next. You can learn more about array based problems in the Arrays category.



