Java Split String Into Array Of Integers Example

The String.split() method splits a String into an array of substrings given a specific delimiter. If we know that each substring represents a number or an integer, we may prefer to convert the output of String.split() into an array of integer.

Java Split String Into Array Of Integers Example

There is no built-in utilty class that can convert an String array to an int Array. There may be utilities out there, but those are third party and not part of the standard package. We need to code manually by invoking the parseInt method of the Integer class on each substring. Here is an example code:
public class Test {
   public static void main(String[] args) {
      String sampleString = "101,203,405";
      String[] stringArray = sampleString.split(",");
      int[] intArray = new int[stringArray.length];
      for (int i = 0; i < stringArray.length; i++) {
         String numberAsString = stringArray[i];
         intArray[i] = Integer.parseInt(numberAsString);
      System.out.println("Number of integers: " + intArray.length);
      System.out.println("The integers are:");
      for (int number : intArray) {

There should be a single loop to go through each element to perform the conversion

Here is the output of the code:

Number of integers: 3
The integers are:

String Tutorials And Examples