liveBook · Manning

Split

As explained in 100 Java Mistakes and How to Avoid Them

Split is an operation or function that divides a string or sequence into parts according to a separator, pattern, or other rule.

Java String.split() accepts a regular expression, not a literal delimiter. Passing "." therefore treats every character as a delimiter because the dot means “any character,” rather than splitting java.util.concurrent at its dots. section 6.5

Escape literal delimiters

String[] parts = javaPackage.split("\\\\."); Alternatively, use Pattern.quote(".") when the delimiter should always be literal. Java processes the string-literal escape first, so the backslash needed by the regular expression must itself be escaped. section 6.5

Account for split() limits and choose an appropriate literal-splitting alternative:

  • The default limit of zero removes trailing empty strings; pass -1 when trailing empty matches must be preserved. section 6.5
  • Use a positive limit to stop splitting after a specified number of parts. section 6.5
  • For literal delimiters, consider Pattern.compile(delimiter, Pattern.LITERAL), Guava Splitter, or Apache Commons StringUtils.splitByWholeSeparator. section 6.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains regex interpretation, Java escaping, limit semantics, and literal-splitting alternatives.
Examples
Uses java.util.concurrent, a comma-separated string with trailing commas, and literal-dot splitting.
What you can do after
Apply Java String.split() safely with escaped or quoted delimiters and deliberate limit values.
How it connects
Connects split() with regular expressions, Pattern.quote(), Pattern.LITERAL, and trailing empty strings.

Also explained in

Compare how 11 books explain split →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.