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

Description :

This java tutorial shows how to use the split() 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 and the tokens are limited using the method parameter limit.

Method Syntax :

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

Parameter Input :

[table]
DataType|Parameter|Description
String|regex|The java regular expression to be used in evaluating how to split the string
int|limit|the maximum number of tokens the string will be splitted
[/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 and the number of tokens will be limited with the parameter limit.

Compatibility Version :

Requires Java 1.4 and up

Exception :

PatternSyntaxException

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

Discussion :

The string split method is helpful only on circumstances that we would want only a specific part of a string to be tokenize. The split string is helpful in converting a string object delimited with regex pattern into tokens. These tokens are stored in an array object, thus we will have now individual access for each string elements.

Java Code Example :

This example source code demonstrates the use of split(regex,limit) method of String class. Basically it just converts a String object in the format Name:AGE:Country into a String array. On the example we have provided there are 3 possible tokens that we could get, however we put only a limit of 2 thus our array will be 2 elements only. The first element would contain “Name” token and the second token would be “AGE:Country”.

Sample Output :

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

string split method example

string split method example

Exception Scenario :

Similar Method :

  • java.lang.String split(String regex)

Suggested Reading List :