Java String split() Method

The split() method in Java is a method of the String class that splits a string into an array of substrings based on a specified delimiter (regular expression). It is commonly used when you need to break down a string into multiple parts based on certain delimiters, such as spaces, commas, or other special characters.

Syntax:


public String[] split(String regex)

Note: regex (String) – A regular expression that defines the delimiter. The string will be split wherever this regular expression matches.

Important Points:

  1. The method returns an array of String objects.
  2. If no delimiter is found, the array will contain one element—the original string.
  3. If the delimiter matches at the start or end of the string, empty strings may be included in the result.

Example:


public class SplitExample {
    public static void main(String[] args) {
        String str = "Apple,Banana,Mango,Orange";
        
        // Split the string by comma
        String[] fruits = str.split(",");
        
        // Print the resulting array
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Mango
Orange

Using the limit Parameter

The limit parameter controls how many parts the string should be split into. If limit is positive, the string will be split into at most limit parts.

Syntax:


public String[] split(String regex, int limit)

limit (int, optional) – Specifies the maximum number of splits to be made. If limit is positive, the array will contain at most limit elements. If limit is zero or negative, the string is split as many times as possible.

Example:


public class SplitExample {
    public static void main(String[] args) {
        String str = "Apple,Banana,Mango,Orange";
        
        // Limit the number of splits to 2
        String[] fruits = str.split(",", 2);
        
        // Print the resulting array
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana,Mango,Orange

If no delimiter is found

If no delimiter is found, the method will return an array with the original string.


public class SplitExample {
    public static void main(String[] args) {
        String str = "Apple";
        
        // Try to split by comma (which doesn't exist in the string)
        String[] fruits = str.split(",");
        
        // Print the resulting array
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output: Apple