The split() method in Java breaks a string into an array of substrings based on a delimiter (a regular expression). It’s one of the most used string methods for parsing data, reading CSV files, or extracting tokens from user input. The method is part of the String class, so you don’t need to import anything extra. You’ll just need a basic Java environment (JDK and an IDE or text editor) to follow along.
What You’ll Need
- Java Development Kit (JDK) 8 or later (the method works in all versions, but newer versions have no extra features for this method).
- A text editor or IDE (like IntelliJ, Eclipse, VS Code, or even Notepad).
- Basic familiarity with Java syntax: variables, arrays, and printing to console.
Step-by-Step
- Understand the two
split()overloads. The first isString[] split(String regex)which splits the string wherever the regex matches. The second isString[] split(String regex, int limit)which also splits but lets you control how many times the split happens. - Create a string to split. For example:
String data = "apple,banana,cherry"; - Call
split()with a simple delimiter. Since a comma is not a special regex character, you can do:String[] fruits = data.split(",");This returns an array with three elements: “apple”, “banana”, “cherry”. - Iterate over the resulting array. Use a for-each loop:
for (String fruit : fruits) { System.out.println(fruit); }This will print each fruit on a new line. - Use a regex for more complex delimiters. If your string uses multiple spaces or punctuation, you can use a regex like
"\\s+"to split on any whitespace. Example:String sentence = "Java is fun"; String[] words = sentence.split("\\s+");The double backslash is needed in Java strings to represent a single backslash in the regex. - Handle special regex characters. If your delimiter is a dot (.), pipe (|), or backslash (\), you must escape it. For a dot, use
"\\."(in Java code:"\\."). For a pipe, use"\\|"(Java code:"\\|"). For a backslash, use"\\\\"(Java code:"\\\\"). - Use the
limitparameter to control the number of splits. For example,data.split(",", 2)returns an array with two elements: the first is “apple”, and the second is the rest of the string “banana,cherry”. A limit of -1 keeps all trailing empty strings, while a limit of 0 (the default) removes trailing empty strings. - Test with empty strings. If your string has consecutive delimiters, like “a,,b”, splitting with
split(",")will produce an array with an empty string in the middle: [“a”, “”, “b”]. Trailing empty strings are removed by default, so “a,b,” gives [“a”, “b”]. - Use
split()with aStringTokenizeralternative if you need to handle quoted commas (like in CSV). The built-insplit()does not handle quotes, so you may need a custom parser or a library like Apache Commons CSV.
Common Mistakes
- Forgetting to escape regex metacharacters. Using
split(".")will split on every character, not on a literal dot. Always escape dots, pipes, and backslashes. - Using
split()on a null string. This will throw aNullPointerException. Always check for null before calling. - Assuming
split()modifies the original string. It doesn’t; it returns a new array. The original string remains unchanged. - Ignoring trailing empty strings. By default,
split()removes trailing empty strings. If you need them, use a negative limit. - Using
split()with a complex regex that causesPatternSyntaxException. If your regex is invalid, it will throw an exception. Test your regex separately.
Tips
- Use
String.join()to reverse the process. To combine an array back into a string, useString.join(",", fruits). - For simple CSV parsing, consider using a library like OpenCSV. It handles quoted fields and line breaks correctly.
- If you need to split on multiple delimiters, use a regex character class. For example,
split("[,;]")splits on either a comma or a semicolon. - Use
Pattern.quote()to escape a literal string. If your delimiter is a user-input string, wrap it withPattern.quote(delimiter)to treat it as a literal. - Be mindful of performance.
split()compiles the regex each time. If you split many times with the same pattern, precompile it usingPattern.compile()and usepattern.split().
Troubleshooting
- Split doesn’t split at all. Check if your delimiter is a regex metacharacter. For example, if you used
split(".")on “a.b.c”, you’ll get an empty array because the dot matches every character, and the result is split into empty strings. Usesplit("\\.")instead. - Array has fewer elements than expected. This often happens because trailing empty strings are removed. If you need them, use
split(regex, -1). - Array has an empty first element. If the string starts with the delimiter, the first element will be an empty string. For example, “,a,b”.split(“,”) gives [“”, “a”, “b”]. This is normal.
- Receiving
PatternSyntaxException. Your regex is invalid. Check for unmatched parentheses or invalid escape sequences. Test the regex in a regex tester. - Split on newline characters doesn’t work. In Java, use
"\\r?\\n"to handle Windows (CRLF) and Unix (LF) line endings. Or useSystem.lineSeparator()but note it’s platform-dependent.
Frequently Asked Questions
- Can I split a string into individual characters? Yes, but it’s inefficient. Use
toCharArray()instead. If you must usesplit(), you can split on an empty regex:"abc".split("")gives [“a”, “b”, “c”], but this is not recommended. - What does
split()return for an empty string? For an empty string,"".split(",")returns an array with one empty string: [“”]. If you use a negative limit,"".split(",", -1)also returns [“”]. - How do I split a string by whitespace including tabs and newlines? Use the regex
"\\s+"which matches any whitespace character (space, tab, newline, etc.) one or more times. - Is
split()thread-safe? Yes, because strings are immutable and the method only reads the string. However, if you use a sharedPatternobject, it is also thread-safe for splitting. - Can I split a string by a pipe character? Yes, but you must escape it:
"a|b".split("\\|")works. Without escaping, the pipe is an alternation operator in regex, which would split on empty matches, giving an array of characters. - Why does
split()remove trailing empty strings? This is the default behavior of thesplit(regex)method, which internally uses a limit of 0. To keep trailing empty strings, pass a negative limit like-1.
Related
- Select a Cell and Highlight Whole Row in Excel
- Number 14 Balloon Drawing: Step-by-Step Guide
- SQL COUNT DISTINCT: Syntax, Examples, and Pitfalls
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- SPLIT_PART in Snowflake: Syntax, Examples, and TipsSnowflake’s SPLIT_PART function returns one piece of a string separated by a delimiter. Its basic syntax is SPLIT_PART(string,…
- Multiple SUMIFS in Google Sheets: Criteria and ExamplesYes. In Google Sheets, use one SUMIFS for conditions that must all be true, and add separate SUMIFS…
- How to Make a Monthly Budget Planner in Google SheetsTo make a monthly budget planner in Google Sheets, create one tab for your budget and another for…
- Excel Data Validation Must Be a Date? No—Here’s HowNo, Excel data validation does not have to be a date. You can restrict entries to whole numbers,…
- How to Autofit a Column in Excel to Fit Its ContentsTo AutoFit a column in Excel for Microsoft 365 on Windows, point to the right edge of its…
- Password Protect an Excel Sheet as Read-OnlyYes. In Excel for Microsoft 365 on Windows, use File > Save As > Browse, open Tools >…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.