In Java, String.split(String regex, int limit) with a limit of -1 means the pattern is applied as many times as possible, and trailing empty strings are kept in the resulting array. This is the key difference from the one-argument split(String regex), which discards trailing empty strings. For example, "a,b,".split(",", -1) returns ["a", "b", ""], while "a,b,".split(",") returns ["a", "b"].
Background: The Two split() Methods
Java’s String class has two overloaded split methods. The first takes only a regex: public String[] split(String regex). The second takes a regex and an integer limit: public String[] split(String regex, int limit). The one-argument version is actually defined as calling the two-argument version with a limit of zero: split(regex, 0). This subtle detail is the root of most confusion about trailing empty strings.
The limit parameter controls how many times the pattern is applied and what happens to the end of the string. The official Java documentation describes three cases:
- Positive limit (n > 0): The pattern is applied at most n-1 times, and the array’s length will be no greater than n. The last element contains the remainder of the string, including any separators.
- Zero limit (n == 0): The pattern is applied as many times as possible, and trailing empty strings are removed from the array.
- Negative limit (n < 0): The pattern is applied as many times as possible, and trailing empty strings are not removed.
So -1 is just one of many negative numbers; any negative value behaves the same way.
How split(regex, -1) Works Under the Hood
Internally, split uses a java.util.regex.Pattern to match the delimiter. The implementation scans the input string, finds each match of the regex, and creates substrings between matches. The limit parameter directly influences the loop that collects these substrings.
For a negative limit, the loop continues until the end of the input, and every substring is added to the result list, including empty strings that appear after the last delimiter. For example:
String csv = "apple,banana,,";
String[] parts = csv.split(",", -1);
// parts = ["apple", "banana", "", ""]
Notice there are two empty strings: one for the empty field between the two commas, and one for the empty field after the final comma. The zero-limit version would drop both trailing empties, giving ["apple", "banana"].
It is also worth noting that split does not treat an empty string as a special case. If the input is "", "".split(",", -1) returns an array with one element: [""], because there is one empty substring before the (nonexistent) delimiter. The zero-limit version returns an empty array [].
When to Use limit = -1 vs. limit = 0
Choosing between -1 and 0 (or the one-argument version) depends entirely on whether trailing empty strings carry meaning in your data.
- Use
-1when: You are parsing a format where fields are positional, such as CSV files, where trailing commas indicate empty fields. For example, a line like"1,2,"should produce three fields. Usingsplit(",")would silently lose the third field, corrupting your data. - Use
0(or one-argument) when: You are splitting natural text or simple lists where trailing delimiters are accidental or meaningless. For instance, splitting a sentence on spaces:"Hello world ".split(" ")gives["Hello", "world"], which is usually what you want.
A common mistake is using the one-argument version for CSV parsing and then wondering why the last column is missing. The fix is simple: use split(",", -1).
Common Problems and Misconceptions
One frequent misconception is that split(",", -1) keeps all empty strings, including those in the middle. That is true, but it is not unique to -1; the zero-limit version also keeps middle empty strings. The only difference is at the end. For example, "a,,b".split(",") returns ["a", "", "b"] because the empty string between the two commas is not trailing.
Another issue arises with regex special characters. The argument to split is a regular expression, not a literal string. If you want to split on a literal dot or pipe, you must escape it: "a.b".split("\\.") or use Pattern.quote("."). Forgetting this leads to surprising results. For example, "a.b".split(".") returns an empty array because . matches every character, and the zero-limit discards trailing empties.
A third pitfall is performance with very long strings and complex regexes. The regex engine can be slow, but for typical delimiters like commas or spaces, it is fine. If you need extreme performance, consider using StringTokenizer (legacy) or a manual loop with indexOf.
Comparing split with Other Parsing Approaches
Java offers several ways to split strings, and each has trade-offs.
| Method | Trailing empty strings | Regex support | Performance |
|---|---|---|---|
split(regex) |
Removed | Yes | Good |
split(regex, -1) |
Kept | Yes | Good |
StringTokenizer |
Never included | No (delimiter is literal) | Fast |
Manual indexOf loop |
You control it | No | Fastest |
For simple delimiters, a manual loop can be more efficient, but split is more readable. For CSV-like data, many developers use a dedicated library like Apache Commons CSV, which handles quoting and edge cases that split cannot. But for quick tasks, split(regex, -1) is often sufficient.
Practical Examples in Real Code
Let's look at a realistic CSV parsing scenario. Suppose you have a line with a trailing comma:
String line = "John,Doe,30,";
String[] fields = line.split(",", -1);
System.out.println(fields.length); // prints 4
System.out.println(fields[3].isEmpty()); // prints true
With the one-argument version, fields.length would be 3, and you would lose the last empty field. This matters when you are reconstructing records or when the number of fields is fixed.
Another example: splitting a path on the file separator. On Windows, paths use backslashes, which must be escaped in regex: "C:\\Users\\name".split("\\\\", -1). On Unix, it's simpler: "/home/user".split("/", -1) gives a leading empty string because the path starts with a delimiter.
Alternatives and Best Practices
If you find yourself frequently dealing with trailing empty strings, consider using split(regex, -1) as a default, then explicitly remove trailing empties if you don't need them. For example, you can use Arrays.copyOf or a loop to trim the array. However, the cleanest approach is to decide based on the data format.
For CSV files, the RFC 4180 standard implies that trailing commas represent empty fields, so -1 is the correct choice. For log lines or user input, trailing delimiters are usually noise, so the default split is fine.
One best practice is to always test your split with sample data that includes edge cases like empty strings, leading delimiters, and consecutive delimiters. This will reveal whether you need the negative limit.
Frequently Asked Questions
What does split(",", -1) do in Java?
It splits the string on every comma and keeps all resulting substrings, including empty strings at the end. For example, "a,b,".split(",", -1) returns ["a", "b", ""].
Why does split() remove trailing empty strings by default?
Because the one-argument split calls split(regex, 0), and a limit of zero explicitly removes trailing empty strings. This was designed to make common cases like splitting sentences cleaner, but it can be surprising for data parsing.
Is there any performance difference between split(regex) and split(regex, -1)?
No significant difference. Both compile the regex and scan the string once. The only difference is whether the final list of substrings is trimmed of trailing empties, which is a trivial operation.
Can I use split with a limit of -2 or any other negative number?
Yes, any negative limit behaves exactly like -1. The Java documentation specifies that a negative limit means the pattern is applied as many times as possible and trailing empty strings are kept.
How do I split a string on a literal dot or pipe?
You must escape the regex metacharacter. For a dot, use split("\\.") or split(Pattern.quote(".")). For a pipe, use split("\\|"). The backslash itself must be escaped in a Java string literal.
Does split(regex, -1) handle Unicode characters correctly?
Yes, Java's regex engine works on UTF-16 code units, so it handles most Unicode characters correctly. However, some Unicode code points outside the Basic Multilingual Plane are represented as surrogate pairs, and the regex engine treats them as two characters. For most practical delimiters, this is not an issue.
Related
- Can C++ Be Split? Yes—Here’s How and Why
- SQL Server COUNT DISTINCT: Syntax, Examples, and Pitfalls
- How to Select a Cell in Excel: Quick Steps
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- LibreOffice Calc Sheet Protection: Setup, Limits, and TipsTo protect a sheet in LibreOffice Calc, open the sheet and choose Tools > Protect Sheet. You can…
- Google Sheets Duplicate Entries: Find, Highlight, RemoveTo find duplicate entries in Google Sheets, use Format > Conditional formatting to highlight repeats, or choose Data…
- How to Add a Watermark in a Word Document on Any PageIn Word for Microsoft 365 on Windows, open the document and choose Design > Watermark to add a…
- How to Split Cells in Half in Excel: 3 Practical MethodsTo split the contents of a cell, select it and use Data > Text to Columns to separate…
- Does Block Sender in Outlook Really Work? What to KnowYes—Outlook’s Block Sender feature works by directing future email from a blocked address to Junk Email, rather than…
- How to Repair Excel Desktop App: Windows Steps and FixesTo repair the Excel desktop app in Microsoft 365 on Windows, close your Office programs, open Windows Settings,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.