0
0
JavaHow-ToBeginner · 3 min read

How to Split String in Java: Syntax and Examples

In Java, you can split a string into parts using the split() method of the String class. You provide a delimiter as a regular expression inside split(), and it returns an array of substrings separated by that delimiter.
📐

Syntax

The split() method divides a string into parts based on a delimiter you specify as a regular expression.

  • string.split(regex): Splits the string wherever the regex matches and returns an array of substrings.
  • regex: A pattern that defines where to split the string (often a simple character like a comma or space).
java
String[] parts = string.split("delimiter");
💻

Example

This example shows how to split a sentence into words using space as the delimiter.

java
public class SplitExample {
    public static void main(String[] args) {
        String sentence = "Java is fun to learn";
        String[] words = sentence.split(" ");
        for (String word : words) {
            System.out.println(word);
        }
    }
}
Output
Java is fun to learn
⚠️

Common Pitfalls

One common mistake is using split() with a dot (.) without escaping it, because dot means "any character" in regex. You must escape special characters with double backslashes (e.g., "\\.").

Also, splitting on an empty string "" splits every character.

java
public class SplitPitfall {
    public static void main(String[] args) {
        String ip = "192.168.1.1";
        // Wrong: dot is special in regex
        String[] wrong = ip.split(".");
        System.out.println("Wrong split length: " + wrong.length);

        // Right: escape dot
        String[] right = ip.split("\\.");
        System.out.println("Right split length: " + right.length);
    }
}
Output
Wrong split length: 0 Right split length: 4

Key Takeaways

Use split() with a regex delimiter to divide strings into parts.
Escape special regex characters like dot (.) with double backslashes.
The method returns an array of substrings split by the delimiter.
Splitting on an empty string splits every character individually.