java.lang.String split(String regex)

Description :

This java tutorial shows how to use the split(String regex) method of String class of java.lang package. This method returns a character array which corresponds to the result of splitting the String object given a java regular expression as a method parameter.

Method Syntax :

public String[] split(String regex)

Parameter Input :

[table]
DataType|Parameter|Description
String|regex|This is the java regular expression that we will be using in splitting the String object
[/table]

Method Returns :

This String split() method with argument regex returns an array of String. The regex parameter will be used in evaluating how we can split the String object.

Compatibility Version :

Requires Java 1.5 and up

Exception :

PatternSyntaxException

This exception will be thrown if and only if the regex pattern specified on the method parameter is invalid.

Discussion :

I really can’t remember how many times do i have to use the split method. This is a very convenient method in breaking down a String object into smaller object based on the pattern provided as regex method parameter.

Supposed we have to break down a pipe(|) delimited String like for example we have a string object “Andrew|M|USA”. As you can see on our string object we have 3 token that we could extract. Using the String split method, we would be able to convert this object into String array.

Java Code Example :

This example source code demonstrates the use of [method name] method of String class. Basically it just converts a String object in the format Name:AGE:Country into a String array.

Sample Output :

Running the split() method example source code of String class will give you the following output

java string split method example

java string split method example

Exception Scenario :

Similar Method :

  • java.lang.String split(String regex, int limit)

Suggested Reading List :