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.
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.
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.
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"};
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) { System.out.println(shape); } }
The output is the same as not specifying a limit:
Number of shapes: 4 Circle Square Rectangle Hexagon
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);