String Split

Su Suriya Ravichandran Updated 14 Nov 2026
5 min read ·Lesson 98 of 133

split breaks a string into an array of substrings wherever a delimiter appears. It is how Java programs read comma-separated values, parse key=value settings, break sentences into words, and separate the parts of dates, paths, and version numbers. The method is simple to call, but its delimiter is a regular expression and its handling of empty fields follows specific rules, both of which are worth understanding precisely.

Basic Use

String csv = "red,green,blue";
String[] colors = csv.split(",");

System.out.println(colors.length);      // 3
System.out.println(colors[0]);          // red
System.out.println(Arrays.toString(colors));   // [red, green, blue]

The delimiter itself is removed; only the text between delimiters is returned. If the delimiter does not appear, the result is a one-element array containing the whole string.

The Delimiter Is a Regular Expression

split(regex) interprets its argument as a regex, so characters with special meaning in regular expressions must be escaped:

"1.2.3".split(".");          // []         "." matches every character
"1.2.3".split("\\.");        // [1, 2, 3]  escaped dot
"a|b".split("\\|");          // [a, b]     | means "or" in a regex
"a|b".split(Pattern.quote("|"));   // [a, b] quote treats the text literally

Characters that need escaping include . $ | ( ) [ ] { } ^ ? * + 0. Pattern.quote(text)` is the safest choice when the delimiter comes from a variable.

Being a regex is also an advantage: one call can split on several delimiters or on variable amounts of whitespace:

"  ada   king  lovelace ".strip().split("\\s+");   // [ada, king, lovelace]
"a, b ;c".split("\\s*[,;]\\s*");                   // [a, b, c]  comma or semicolon, trimming spaces

0s+ (one or more whitespace characters) is the standard way to split text into words. Strip the string first; otherwise leading whitespace produces an empty first element.

Empty Fields and Trailing Empties

Consecutive delimiters produce empty strings, which represent empty fields:

Arrays.toString("a,b,,c".split(","));       // [a, b, , c]
Arrays.toString(",a,b".split(","));         // [, a, b]   leading empty kept

Trailing empty strings, however, are removed by default:

Arrays.toString("a,b,,c,,".split(","));     // [a, b, , c]   last two empties dropped

For data formats where every field position matters, such as CSV rows with optional last columns, this silently loses columns. A negative limit keeps them:

Arrays.toString("a,b,,c,,".split(",", -1)); // [a, b, , c, , ]  6 fields

The limit parameter

split(regex, limit) controls how many pieces are produced:

limitBehavior
0 (the default)Split everywhere; remove trailing empty strings
NegativeSplit everywhere; keep trailing empty strings
Positive nAt most n pieces; the last piece contains the rest of the string, unsplit

A positive limit is ideal when only the first delimiter separates fields and the rest of the text may contain the delimiter:

"a,b,c,d".split(",", 2);                     // [a, b,c,d]
"db.url=jdbc:mysql://host?ssl=true".split("=", 2);   // [db.url, jdbc:mysql://host?ssl=true]

Without the limit, the second = inside the URL would split the value apart.

The empty string

"".split(",");           // one element: [""]  (length 1, not 0)

Splitting an empty string returns an array containing one empty string. Check for blank input before splitting if "no fields" should mean an empty array.

Splitting into Lines

split("\n") misses Windows line endings (\r\n), leaving stray \r characters. Two better options:

String text = "a\r\nb\nc";

text.split("\\R");              // [a, b, c]  \R matches any line break
text.lines().toList();          // [a, b, c]  Java 11+, returns a Stream<String>

Splitting Without Removing: Lookarounds

Zero-width regex constructs split between characters without consuming any:

"Java21".split("(?<=\\D)(?=\\d)");    // [Java, 21]  between a non-digit and a digit
"camelCaseName".split("(?=[A-Z])");   // [camel, Case, Name]

Turning Pieces into Other Types

split returns strings; convert as needed, stripping whitespace first:

String scores = "78, 91 ,64";
int[] values = Arrays.stream(scores.split(","))
        .map(String::strip)
        .mapToInt(Integer::parseInt)
        .toArray();                                // [78, 91, 64]

List<String> tags = Arrays.asList("java,docker,sql".split(","));   // fixed-size list view

Alternatives to split

NeedTool
Split on a single literal character, very frequentlyindexOf + substring, which avoids regex overhead
Split many strings with the same complex patternCompile once: Pattern p = Pattern.compile("0s*,1s*"); p.split(s)
Process pieces lazily as a streamPattern.compile(regex).splitAsStream(s)
Read tokens of mixed types from inputScanner with useDelimiter
Real CSV with quoted fields ("Pen, blue",10)A CSV library such as OpenCSV or Apache Commons CSV

The last point matters: a plain split(",") breaks quoted fields that contain commas. For files produced by spreadsheets or other systems, use a proper CSV parser.

String.split has a fast path: when the delimiter is a single character that is not a regex metacharacter (for example "," or ":"), it splits without the regex engine.

Practical Example: Parsing a Configuration File

Many applications read settings from simple key=value files. The parser must skip comments and blank lines, allow = inside values, report malformed lines, and split list-valued settings.

import java.util.*;

public class Config {
    static Map<String, String> parse(String text) {
        Map<String, String> settings = new LinkedHashMap<>();
        int lineNo = 0;
        for (String raw : text.split("\\R")) {             // \R = any line break
            lineNo++;
            String line = raw.strip();
            if (line.isEmpty() || line.startsWith("#")) continue;
            String[] kv = line.split("=", 2);              // limit 2: '=' allowed in the value
            if (kv.length != 2 || kv[0].isBlank()) {
                System.out.println("Line " + lineNo + " ignored: " + raw);
                continue;
            }
            settings.put(kv[0].strip(), kv[1].strip());
        }
        return settings;
    }

    public static void main(String[] args) {
        String file = """
            # app settings
            app.name = GOCOURSE
            db.url = jdbc:mysql://localhost:3306/lms?ssl=true
            allowed.origins = https://gocourse.in, https://admin.gocourse.in
            broken line without equals
            max.upload.mb=25
            """;

        Map<String, String> cfg = parse(file);
        cfg.forEach((k, v) -> System.out.println(k + " -> " + v));

        List<String> origins = Arrays.stream(cfg.get("allowed.origins").split(","))
                .map(String::strip)
                .toList();
        System.out.println("Origins: " + origins.size() + " " + origins);
        System.out.println("Upload limit: " + Integer.parseInt(cfg.get("max.upload.mb")) + " MB");
    }
}

Output:

Line 5 ignored: broken line without equals
app.name -> GOCOURSE
db.url -> jdbc:mysql://localhost:3306/lms?ssl=true
allowed.origins -> https://gocourse.in, https://admin.gocourse.in
max.upload.mb -> 25
Origins: 2 [https://gocourse.in, https://admin.gocourse.in]
Upload limit: 25 MB

Three different splits do three different jobs:

  • split("0R") breaks the text into lines regardless of the line-ending style.
  • split("=", 2) separates each key from its value. The limit keeps the = inside the database URL as part of the value.
  • split(",") on the origins setting produces a list, and strip removes the space after the comma.

A line without = produces a one-element array, so kv.length != 2 identifies it as malformed and the parser reports it instead of failing. The """ text block holding the sample file is covered in the Text Blocks lesson.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining
Ask about this post
AI Ask about this post

Ask questions about String Split and get answers drawn from it.

Signed-in readers only.