View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Java String split() Method Explained

Updated on 30/05/20256,850 Views

Working with strings is a daily task in Java programming. Often, you need to break a long string into smaller parts—like words, values, or tokens. That’s where the split() method comes into play. It allows developers to divide a string based on a specified delimiter, like a comma, space, or even a regular expression. Whether you're parsing user input or processing file data, this method is essential.

In this blog, you’ll learn what Java String split() is, how it works, and when to use it with multiple real-world examples.

Also, Software engineering courses allow you to explore such Java methods in depth and apply them effectively in real projects.

What is split() in Java?

The split() method in Java programming divides a string into an array of substrings based on a regular expression (regex). It belongs to the String class and is extremely useful when you need to tokenize a string. Think of it like cutting a sentence into words using spaces or breaking a CSV line using commas.

It returns a string array, and the delimiter used to split can be as simple as a comma or as complex as a regex pattern.

Syntax:

String[] split(String regex)
String[] split(String regex, int limit)

Enhance your abilities through these best-in-class certifications.

split(String regex, int limit)

This overloaded method allows you to control the number of times the string should be split. The limit parameter sets the maximum number of resulting substrings. Let’s understand Java String Split method with the help of examples:

Example 1: Specified Low Limit Value

This example shows how the method works when the limit is lower than the number of matches found.

public class SplitExample1 {
    public static void main(String[] args) {
        String input = "Java-is-a-popular-language";
        String[] parts = input.split("-", 2);

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

Java

is-a-popular-language

Explanation: The string is split at the first hyphen. The second element holds the rest of the string because the limit is 2.

Also read: StringTokenizer Class in Java

Example 2: High Limit Value

Here, the limit is higher than the number of matches in Java String Split. 

public class SplitExample2 {
    public static void main(String[] args) {
        String input = "One-Two-Three";
        String[] parts = input.split("-", 5);

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

One

Two

Three

Explanation: The method splits the string at each hyphen. Since the limit is more than needed, it behaves like the regular split().

Example 3: Negative Limit Value

Java String split with a negative limit includes all trailing empty strings in the output array, ensuring no data is discarded after the final delimiter.

public class SplitExample3 {
    public static void main(String[] args) {
        String input = "a,,b,";
        String[] parts = input.split(",", -1);

        for (String part : parts) {
            System.out.println("'" + part + "'");
        }
    }
}

Output:

'a'

''

'b'

''

Explanation: With a negative limit, all possible splits including trailing empty strings are preserved.

Also read: Top 13 String Functions in Java | Java String [With Examples]

Example 4: Limit Value as Zero

A zero limit discards trailing empty strings.

public class SplitExample4 {
    public static void main(String[] args) {
        String input = "a,,b,";
        String[] parts = input.split(",", 0);

        for (String part : parts) {
            System.out.println("'" + part + "'");
        }
    }
}

Output:

'a'

''

'b'

Explanation: Trailing empty substrings are removed when the limit is set to zero.

split(String regex)

The split(String regex) method is a part of the Java String split functionality. It splits the string into an array of substrings based on the specified regular expression. It splits the original string wherever the regex matches and returns all resulting parts as separate elements in the array.

Example 1: String by Colon

This example splits a string using a colon : as the delimiter.

public class SplitExample5 {
    public static void main(String[] args) {
        String input = "key:value:entry";
        String[] parts = input.split(":");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

key

value

entry

Explanation: Each value is separated at the colon, producing three substrings.

Example 2: String by Specific Word "by"

Demonstrates splitting a string using a full word as a delimiter.

public class SplitExample6 {
    public static void main(String[] args) {
        String input = "driven by code by logic";
        String[] parts = input.split("by");

        for (String part : parts) {
            System.out.println(part.trim());
        }
    }
}

Output:

driven

code

logic

Explanation:

The string is split wherever the word "by" occurs.

Example 3: String by Space

An empty string in regex will split between every character.

public class SplitExample7 {
    public static void main(String[] args) {
        String input = "ABC";
        String[] parts = input.split("");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

A

B

C

Explanation:

An empty string regex breaks the input into individual characters.

Must explore: Array in Java: Types, Operations, Pros & Cons

Example 4: String by Dot

In Java String split, the dot (.) is a special regex character and must be escaped as "\." to split by a literal dot correctly.

public class SplitExample8 {
    public static void main(String[] args) {
        String input = "www.google.com";
        String[] parts = input.split("\\.");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

www

google

com

Explanation:

We use \\. to split by the dot since it's a special character in regex.

Example 5: Trailing Spaces

This example shows how trailing whitespace is handled.

public class SplitExample9 {
    public static void main(String[] args) {
        String input = "apple  banana   orange  ";
        String[] parts = input.trim().split("\\s+");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

apple

banana

orange

Explanation: The string is split using one or more spaces with \\s+, and trailing spaces are removed using trim().

Example 6: Regular Expression

In Java String split, you can use regular expressions to split strings. It can be based on complex patterns like multiple delimiters, character groups, or conditional matches for flexible parsing.

public class SplitExample10 {
    public static void main(String[] args) {
        String input = "abc123def456ghi";
        String[] parts = input.split("\\d+");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

abc

def

ghi

Explanation: The regex \\d+ matches one or more digits. It splits the string wherever digits occur.

Must read: String Comparison in Java: Methods, Examples, and Best Practices

Example 7: Delimiter Not Present in the String

If the delimiter is not found, the entire string is returned as a single element.

public class SplitExample11 {
    public static void main(String[] args) {
        String input = "HelloWorld";
        String[] parts = input.split("-");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

Output:

HelloWorld

Explanation: Since the delimiter is absent, the original string remains unchanged.

Use Cases of Java String Split in Real Projects

The Java String split  method is widely used in real-world scenarios:

  • Parsing CSV or TSV data
  • Tokenizing user input in command-line applications
  • Extracting data from logs or reports
  • Breaking down configuration files

Conclusion

The split() method in Java is a powerful tool for breaking strings into manageable parts using regular expressions. Whether you're parsing data, extracting values, or formatting input, understanding how split() works with and without the limit parameter is essential. 

Mastering its use helps write cleaner and more efficient code. To deepen your skills, consider exploring software engineering courses that focus on Java fundamentals and hands-on string manipulation techniques.

FAQs

1. Can split() method throw an exception?

No, the split() method doesn’t throw an exception by default. However, if the regular expression syntax used as a parameter is invalid, it may throw a PatternSyntaxException. It’s important to validate the regex before using it in the method to avoid runtime errors.

2. Is the original string modified after using split()?

No, the original string remains unchanged. Java Strings are immutable, which means any method that appears to modify a string, like split(), actually returns a new result without affecting the original string object.

3. What is the return type of the split() method?

The split() method returns an array of strings (String[]). This array contains substrings split around matches of the specified regular expression. You can then access each part using array indices in a loop or directly.

4. How does the limit parameter affect the split() method?

The limit parameter controls the number of resulting substrings. A positive value limits the number of elements. Zero removes trailing empty strings. A negative value allows all possible substrings, including trailing empty strings.

5. Can we split using special characters like dot or pipe?

Yes, but special characters like dot (.) or pipe (|) are regex metacharacters. You must escape them using double backslashes (\\. or \\|) to split the string correctly without regex conflicts or unexpected behavior.

6. How to split a string by multiple delimiters in Java?

To split using multiple delimiters, you can use a regex pattern with the OR operator (|). For example, split(",|;|\\s") will split the string by commas, semicolons, or spaces. Always escape regex metacharacters properly.

7. What happens if the delimiter is not found in the string?

If the delimiter or regex is not present in the string, the split() method returns an array containing the original string as the only element. It means no splitting occurred due to the absence of the pattern.

8. Can split() handle leading or trailing delimiters?

Yes, it can. If a delimiter appears at the start or end of the string, the method includes empty strings in the resulting array. To remove them, you can post-process the array or adjust the limit parameter accordingly.

9. How does split() behave when used on an empty string?

When used on an empty string with any delimiter, split() returns an array with one empty string element ([""]). If the delimiter matches, it can return an array of multiple empty strings, depending on the pattern and limit.

10. Can we convert the split result into a List or another data type?

Yes, you can convert the result from split() (a String[]) to a List using Arrays.asList(splitArray). This is helpful when you want to use collection operations like filtering, sorting, or iteration with more flexibility.

11. Is it efficient to use split() in performance-critical applications?

While split() is convenient, it's not always the most efficient for high-performance applications. It uses regex internally, which can be slower. For better performance, especially in large-scale parsing, consider using StringTokenizer or manual parsing with indexOf() and substring().

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.