How to Split a String in Java: Java String split() Method Tutorial

In this section, we will learn what the String split() method is and how to use it in Java to split string values.

What is Java String split() Method?

The Java String split() method is used to split a string value into sub-strings and return these sub-strings as a result.

Java split() Method Syntax:

public String split(String regex)

public String split(String regex, int limit)

split() Method Parameters:

  • `regex`: this is the delimiter or the regular expression that we want to apply to the target string and split it based on this delimiter.
  • `limit`: this value is used to limit the number of elements in the returned array.

Note: if we pass the value 0 it means return all the elements of the array without removing any of them.

split() Method Return Value:

The return value of this method is an array that contains the sub-strings of the target string value.

split() Method Exceptions:

The method does not throw an exception.

Example: using String split() method

public class Simple {

    public static void main(String args[]) {
        String str = "Welcome to future";
        String [] strings = str.split(" ");
        for(String s: strings){
            System.out.print(s+", ");
        }
    }
}

Output: Welcome, to, future,

Here, the delimiter is a white space and so each word that is separated via a white space is considered as one element in the returned array.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies