split() takes a regular expression, not a plain string, and by default it removes trailing empty strings. Both behaviours cause bugs: splitting on "." or "|" doesn't do what you expect, and CSV lines with empty last columns lose fields.
Key Points: • Characters like . | * + ? $ ^ ( ) [ ] { } \ are regex symbols. Escape them ("\\.", "\\|") or use Pattern.quote("."). • Trailing empty strings are removed: "a,b,,".split(",") gives [a, b]. Pass a negative limit, split(",", -1), to keep them. • A positive limit caps the number of parts: "k=v=x".split("=", 2) gives [k, v=x]. • Leading empty strings are kept, except when the match at index 0 is zero-width. • For repeated or mixed whitespace, use split("\\s+") after trim(), or strip(). • Real CSV (quoted fields, embedded commas) needs a CSV library rather than split().
Code Example:
import java.util.Arrays;
import java.util.regex.Pattern;
public class SplitPitfalls {
public static void main(String[] args) {
String ip = "192.168.1.10";
System.out.println("split(\".\"): " + Arrays.toString(ip.split(".")));
System.out.println("split(\"\\\\.\"): " + Arrays.toString(ip.split("\\.")));
System.out.println("Pattern.quote: " + Arrays.toString(ip.split(Pattern.quote("."))));
String row = "Asha,Pune,,";
System.out.println("Default: " + Arrays.toString(row.split(",")) + " size " + row.split(",").length);
System.out.println("Limit -1: " + Arrays.toString(row.split(",", -1)) + " size " + row.split(",", -1).length);
System.out.println("Limit 2: " + Arrays.toString("key=value=extra".split("=", 2)));
System.out.println("Pipe: " + Arrays.toString("a|b|c".split("\\|")));
System.out.println("Spaces: " + Arrays.toString(" java spring boot ".trim().split("\\s+")));
}
}Output:
split("."): [] split("\\."): [192, 168, 1, 10] Pattern.quote: [192, 168, 1, 10] Default: [Asha, Pune] size 2 Limit -1: [Asha, Pune, , ] size 4 Limit 2: [key, value=extra] Pipe: [a, b, c] Spaces: [java, spring, boot]
Good to Know: split(".") returns an empty array because "." matches every character, so every part is empty and all of them are removed as trailing empties. It's a favourite trick question, so be ready to explain why the result is [] rather than an error.
Interview Tip: A concise interview answer is:
"split takes a regex, so dots, pipes and other special characters must be escaped or wrapped in Pattern.quote, otherwise split('.') returns an empty array. It also drops trailing empty strings by default, so for CSV-like data I pass a limit of -1 to keep empty columns, and a positive limit when I only want the first few parts."
Previous question: What is the difference between isEmpty() and isBlank(), and how do you safely check for null or empty Strings?
Next question: Why is String a good choice for a HashMap key?