Instance overloaded split(…) methods have below declarations:
1. public String[] split(String regex, int limit) {…}: It returns the String[] after splitting this string around matches of the given regex.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
A. If the limit is positive then the pattern will be applied at most (limit – 1) times, the array’s length will be no greater than limit, and the array’s last entry will contain all input beyond the last matched delimiter. For example,
"BAZAAR".split("A", 1); //returns ["BAZAAR"] as pattern is applied 1 - 1 = 0 time.
"BAZAAR".split("A", 2); //returns ["B","ZAAR"] as pattern is applied 2 - 1 = 1 time.
"BAZAAR".split("A", 3); //returns ["B","Z","AR"] as pattern is applied 3 - 1 = 2 times.
"BAZAAR".split("A", 4); //returns ["B","Z","","R"] as pattern is applied 4 - 1 = 3 times.
"BAZAAR".split("A", 4); //returns ["B","Z","","R"] as pattern needs to be applied 5 - 1 = 4 times but it is applied 3 times (which is max).
":".split(":", 2); //returns ["",""] as pattern is applied (2 - 1) time and there is an empty space ("") before and after ":", so resulting array contains two empty strings.
B. If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. For example,
"BAZAAR".split("A", 0); //returns ["B","Z","","R"].
":".split(":", 0); //returns blank array as both the empty strings are discarded.
C. If the limit is negative then the pattern will be applied as many times as possible and the array can have any length. For example,
"BAZAAR".split("A", -10); //returns ["B","Z","","R"] as pattern is applied max times, which is 3.
":".split(":", -2); //returns ["",""] as pattern is applied max times, which is 3.
2. public String[] split(String regex) {…}: It returns the String[] after splitting this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
"BAZAAR".split("A"); //returns ["B","Z","","R"] as this statement is equivalent to "BAZAAR".split("A", 0);.
":".split(":"); //returns blank array as this statement is equivalent to ":".split(":", 0);.