Java String split removed empty values
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Java's String.split() does not remove all empty values. It specifically removes trailing empty strings from the result array when you use the default one-argument form. Empty strings in the middle of the input are preserved. To keep trailing empty values, pass -1 as the second argument: split(delimiter, -1).
This behavior catches many developers off guard, especially when parsing delimited data where empty fields carry meaning.
How the Limit Parameter Works
The split method has two overloads:
The one-argument form behaves as if you passed limit = 0. The limit parameter controls two things: how many times the pattern is applied, and whether trailing empty strings are included.
| Limit Value | Pattern Applications | Trailing Empty Strings |
0 (default) | Unlimited | Removed |
-1 | Unlimited | Preserved |
n > 0 | At most n - 1 times | Preserved |
Default behavior (limit = 0)
Negative limit (limit = -1)
Positive limit (limit = 3)
Middle Empty Values Are Always Preserved
A critical detail: only trailing empty strings are affected by the default limit. Empty strings between non-empty values survive regardless.
This asymmetry is the root of most confusion. Developers expect consistent behavior for all empty fields, but the spec only drops trailing ones.
The Delimiter Is a Regular Expression
Another common source of bugs is forgetting that split() treats its first argument as a regular expression, not a plain string. Characters with special meaning in regex must be escaped.
Characters that need escaping in regex: ., |, *, +, ?, (, ), [, ], {, }, ^, $, \.
Use Pattern.quote for Dynamic Delimiters
When the delimiter comes from user input or configuration, hand-escaping is error-prone. Use Pattern.quote() to treat any string as a literal:
Real-World Scenarios
Parsing CSV-like Data
When processing pipe-delimited or tab-delimited export files, trailing empty fields represent real data (for example, a nullable column with no value). Using the default split drops those fields and shifts all subsequent column indices.
Processing Configuration Values
Using a positive limit here prevents the split from breaking on the second = sign, which is part of the value.
Counting Occurrences
Comparison: split vs. StringTokenizer vs. Guava Splitter
| Feature | String.split() | StringTokenizer | Guava Splitter |
| Trailing empties | Dropped by default | Always dropped | Configurable |
| Regex support | Yes | No | Optional |
| Empty token handling | Middle preserved | Always dropped | Configurable |
| Return type | String[] | Enumeration | Iterable<String> |
| Thread-safe | Yes (immutable) | No | Yes (immutable) |
If you need full control over empty value handling, Guava's Splitter is the most explicit API:
When to Use split vs. a Real Parser
String.split() works for simple delimited data where fields never contain the delimiter character. It breaks down when the format supports quoting or escaping.
For CSV, TSV with quoting, or any structured text format, use a dedicated parser like OpenCSV, Apache Commons CSV, or Jackson CSV. split() is not a format parser.
Common Pitfalls
Assuming all empty values are removed is the most common mistake. Only trailing empty strings are discarded by the default one-argument form. Middle empties survive.
Forgetting that the delimiter is a regex causes silent bugs. Splitting on . without escaping matches every character and produces an empty array (all elements are trailing empties that get removed).
Using split(",") for CSV data and expecting it to handle quoted commas, escaped delimiters, or multiline fields leads to broken parsing. Use a real CSV library.
Relying on the default limit when field count matters produces arrays with fewer elements than expected, causing ArrayIndexOutOfBoundsException downstream when code accesses fields by position.
Using split(delimiter, -1) on user input without validating the result length can introduce injection risks if the code assumes a fixed number of fields.
Summary
String.split()removes trailing empty strings by default because it uses a limit of0.- Empty strings in the middle of the input are always preserved.
- Pass
-1as the second argument to keep all trailing empty fields. - The delimiter is a regex. Escape special characters or use
Pattern.quote(). - Use a positive limit (
split("=", 2)) to control the maximum number of splits. - For structured formats with quoting or escaping, use a dedicated parser instead of
split().
Related reading
- Java string split with . (dot)
- Java string to date conversion
- Java String to SHA1
- Java sun.security.provider.certpath.SunCertPathBuilderException unable to find valid certification path to requested target
- Java Swing revalidate vs repaint
- Java switch statement Constant expression required, but it IS constant
- Java Synchronized Block for .class
- Java synchronized method

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.