HOWTO · Java

How to Convert String to Int Array in Java

This article introduces methods to convert String to int array in Java.

On this page

When a Java program receives bracketed, comma-separated integer text such as "[1, 2, 3]", remove the brackets, split on commas, and parse each token into an int. The result is a primitive int[]. The examples below assume this exact format; use a parser designed for the actual format if the input is JSON or follows another grammar.

Choose a conversion approach

Use replaceAll() with split() for a short conversion, Java 8 streams when you prefer a compact pipeline, or StringTokenizer when processing tokens with a delimiter set. All three approaches ultimately call Integer.parseInt(). The stream example requires Java 8 or later; the other examples use standard Java APIs as well. Choose one approach and adapt its input validation to the guarantees made by your data source.

Use replaceAll() and split()

This example removes each square bracket, separates the remaining text at commas, trims each token, and stores parsed values in an integer array.

Run this example:

import java.util.Arrays;

public class ConvertStringToIntArray {
  public static void main(String[] args) {
    String text = "[1,2,3]";
    String[] tokens = text.replaceAll("[\\[\\]]", "").split(",");
    int[] values = new int[tokens.length];

    for (int i = 0; i < tokens.length; i++) {
      values[i] = Integer.parseInt(tokens[i].trim());
    }

    System.out.println(Arrays.toString(values));
  }
}

replaceAll() accepts a regular expression, while split() also interprets its delimiter as a regular expression. Trimming lets the same loop accept spaces around numbers. This basic conversion expects bracketed comma-separated input and does not validate the brackets before removing them.

Use Java 8 streams

Streams express the same sequence as a pipeline: remove the outer characters, split the contents, trim each token, parse it, then collect the primitive results with toArray(). This class is complete and can be compiled on Java 8 or later.

import java.util.Arrays;

public class StringToIntUsingJava8Stream {
  public static void main(String[] args) {
    String text = "[1, 2, 3]";
    int[] values = Arrays.stream(text.substring(1, text.length() - 1).split(","))
        .map(String::trim)
        .mapToInt(Integer::parseInt)
        .toArray();

    System.out.println(Arrays.toString(values));
  }
}

substring(1, text.length() - 1) assumes that the first and last characters are the expected brackets. Validate those characters before using this shortcut when input is not trusted.

Use StringTokenizer

StringTokenizer treats its delimiter argument as a set of delimiter characters. In this example, either a comma or a square bracket ends a token. Trim each token before parsing so spaces after commas are accepted.

import java.util.Arrays;
import java.util.StringTokenizer;

public class StringToIntUsingStringTokenizer {
  public static void main(String[] args) {
    String text = "[1, 2, 3]";
    StringTokenizer tokenizer = new StringTokenizer(text, "[],");
    int[] values = new int[tokenizer.countTokens()];
    int index = 0;

    while (tokenizer.hasMoreTokens()) {
      values[index++] = Integer.parseInt(tokenizer.nextToken().trim());
    }

    System.out.println(Arrays.toString(values));
  }
}

Unlike split(), StringTokenizer skips repeated delimiters and does not produce a token for an empty field. That behavior can conceal a missing value, so prefer explicit validation when every comma-separated position is required.

Handle whitespace and invalid numbers

Integer.parseInt() accepts an optional sign and decimal digits, but it does not ignore surrounding whitespace; call trim() on each token first. An empty string, an empty field such as the middle item in [1,,3], or text such as x cannot be parsed. The default split() behavior also drops trailing empty fields, so [1,2,] may not reveal the final missing value unless you use split(",", -1) and validate every token. StringTokenizer skips repeated delimiters, which likewise means it cannot report an empty field by itself.

Malformed text and values outside the int range cause Integer.parseInt() to throw NumberFormatException. Catch that specific exception if the program can recover, and report which token failed or reject the whole input. If a catch block merely continues after assigning into a preallocated array, the untouched slot keeps Java’s default value, 0; that zero is not a successful parse. For reliable input, check the bracket structure and confirm that every required token is present before accepting the resulting array.