Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The Java string split() method is used to return a string array containing elements obtained by splitting the given string around matches of the given regular expression.

Syntax

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

Parameters

regex specify the delimiting regular expression.
limit specify the result threshold, the number of elements of the array to be returned.

Return Value

Returns the array of strings computed by splitting the string around matches of the given regular expression.

Exception

throws PatternSyntaxException, if the regular expression's syntax is invalid.

Example:

In the below example, split() method to used to return the string array computed after splitting the given string by specified regex expression.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello-Cello-Hullo-Hallo-Jello";

    //split the string by "-" regex expression
    String[] Arr = MyString.split("-");
    
    //print the content of the string array
    System.out.println("Arr contains: ");
    for(String str: Arr)
      System.out.println(str);
  }
}

The output of the above code will be:

Arr contains: 
Hello
Cello
Hullo
Hallo
Jello

Example:

In the below example, split() method to used with limit argument, which is used to specify the number of elements of the array to be returned.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello-Cello-Hullo-Hallo-Jello";

    //split the string by "-" regex expression
    String[] Arr = MyString.split("-", 3);
    
    //print the content of the string array
    System.out.println("Arr contains: ");
    for(String str: Arr)
      System.out.println(str);
  }
}

The output of the above code will be:

Arr contains: 
Hello
Cello
Hullo-Hallo-Jello

❮ Java String Methods