Java String Split Limit Examples

The split method of the Java String class splits the given string into substrings given a delimiter. The result is an array of String. We may specify the maximum number of items returned by using specifying the limit. Java String Split Limit examples will be shown below.

String.split() syntax

Here is the syntax of the String split method:

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

The first parameter is the delimiter while the second one is the limit on the resulting list.

Limit examples

Here is an exammple when the number of items is more than the specified limit.
String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 2);
As we could see, there are 4 potential items in the resulting list. Since the limit 2 is specified, the array list return contains only 2 Strings. Here is the equivalent String array for the code above:
String[] shapes = {"Circle", "Square,Rectangle,Hexagon"};
Notice that after the first occurrence of comma, the remaining characters were concatenated together as the second element of the resulting String array.
Here is the same original string but passing the limit value 3:
String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 3);
This will be the equivalent resulting value.
String[] shapes = {"Circle", "Square", "Rectangle,Hexagon"};
Take note again the value of the last element.

Large Limit Examples

However, if we pass a limit value that is more than the number of possible elements, the limit is ignored. Here is an example:

String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 10);

Since the number of items is less than 10, all items were returned in the resulting String array. Here is the equivalent String array:
String[] shapes = {"Circle", "Square", "Rectangle", "Hexagon"};

Zero or Negative Limit Examples

When the value passed for limit is zero or negative, it is the same as telling the split method to not limit the result. Here is an example:

public static void main(String[] args) {
   String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 0);
   System.out.println("Number of shapes: " + shapes.length);
   for (String shape : shapes) {

The output is the same as not specifying a limit:

Number of shapes: 4

These have the same contents:

String[] shapes1 = "Circle,Square,Rectangle,Hexagon".split(",", 0);
String[] shapes2 = "Circle,Square,Rectangle,Hexagon".split(",", -1);
String[] shapes3 = "Circle,Square,Rectangle,Hexagon".split(",", -2);

String Tutorials And Examples