Course contentsShow
← Java
Lesson 2208 of 2,87043. String Handling in DepthFree lesson

Limit Parameter in split(): Controlling Array Size

Understand how the limit parameter controls the number of splits and affects trailing empty strings in the result.

Limit Parameter in split(): Controlling Array Size

What you'll learn: How to use the limit parameter in split() to control how many times splitting occurs and whether trailing empty strings appear in the result.

The Core Idea

The split() method has an overloaded version that accepts a second parameter called limit. This integer controls the maximum number of array elements returned and determines how trailing empty strings are handled.

String[] parts = text.split(regex, limit);

How the Limit Parameter Works

The limit parameter behaves in three distinct ways:

Positive limit: The pattern is applied at most limit - 1 times. The array length won't exceed limit, and the last element contains all remaining input, even if more delimiters exist.

String text = "apple,banana,cherry,date";
String[] parts = text.split(",", 2);
// Result: ["apple", "banana,cherry,date"]
// Split only once, rest goes into second element

Zero limit: Splits as many times as possible and discards trailing empty strings.

String text = "a,b,c,,,";
String[] parts = text.split(",", 0);
// Result: ["a", "b", "c"]
// Trailing empty strings removed

Negative limit: Splits as many times as possible and keeps trailing empty strings.

String text = "a,b,c,,,";
String[] parts = text.split(",", -1);
// Result: ["a", "b", "c", "", "", ""]
// All empty strings preserved

Why This Matters

Think of limit like setting a "budget" for splitting. A positive limit says "stop early and save the rest," zero says "split everything but tidy up the end," and negative says "split everything, keep it all."

Key Takeaway: The limit parameter in split() controls both the maximum number of splits performed and whether trailing empty strings are included—positive limits stop early, zero removes trailing empties, and negative preserves all results.