How to use split() in Java? String split() Java method

In this Java tutorial, I will explain How to use split() in Java? Also, we will explore different useful scenarios to understand What is split() in Java? and How to properly use String split() Java method with Top 5 use cases.

The split() method is an instance method of java.lang.String class. In the beginning, most of the Java developers think that the split() method accepts a string to split the string object from all those parts that get matched. But it’s not completely true!

  • The String split() in Java always accepts a special string something known as ‘Regular Expression’.
  • Unlike regular strings, which are just a group of characters in “double quotes”, the Regular Expressions are capable enough to find/match all substrings similar to the pattern provided as a 1st parameter in the split() method.

Let’s see the- The Top 5 use cases of split() method in Java. But, first thing first-

What is split() String method in Java?

The split() method allows us to break a given string around the matches of a given substring or regular expression. This substring or expression is also known as delimiter.

  • To use the split() String Java method, you must have a String object.
  • Using the String object, you can call split() String method by passing a delimiter (and the limit of results as a second parameter, if necessary).

However, in most of the cases, this delimiter is a comma(,), space( ) or a period(.)

Syntax:

split​( String regularExpression )                     // returns String [ ]
split​( String regularExpression, int limit )    // returns String [ ]

 

  • Both of the variants of split() method return a String type 1-dimensional array.
  • It means, after breaking the desired string according to the passed substring or expression, you will get an array.

Anyone who has done some programming knows the Importance of an Array data structure in OOP or anywhere. That’s why I suggest all Java programmers join a comprehensive Object Oriented Java course like Object Oriented Java Programming: Beyond Specialization course to Deep dive in Java on Coursera to fill all the deadly gaps for better understanding.

split() String Examples

The split() method can be used with many cases, just because of covering a wide range of patterns of String (thanks to Regular expression – covered later in this post).

Let’s explore 5 major use cases of split() method:

1) How to split a string in Java using Comma (,)

Assume, you have a string like this-
String strBooks = "Java,Data Structure,C++,Python";    //  A string with comma (,)
And, you want to break this string using a comma as a delimiter. Below is the demonstration of what you should do and how split() works?
Split() method is used to split a string on the basis of regular expressions.
Example 1:
// Program: How to split a string using a comma (,)

import java.util.Arrays;

public class FirstSplitExample
{
    public static void main( String[] arguments)
    {
        String strBooks = "Java,Data structure,C++,Python";    // A string containing comma (,) 
        String[] booksArray = strBooks.split(",");                          // Splitting the string by , comma

        System.out.println( Arrays.toString(booksArray));
        // Output: [Java, Data structure, C++, Python]
    }
}

 

2) How to split a string using a dash or the hyphen ()?

Assume you have a string like this-
String strPhoneNo = "203-888765";
And, you want to break this string using a hyphen or dash () as a delimiter. Below is the demonstration of what you should do and how to split() it?
Example 2:
// Program: How to split a string using a hyphen or dash (-)

import java.util.Arrays;

public class SecondSplitExample
{
    public static void main( String[] arguments)
    {
        String strPhoneNo = "203-888765";                                        // A string containing dash or hyphen (-) 
        String[] partsPhoneNum = strPhoneNo.split("-");                 // Splitting the string by - hyphen (or dash)

        System.out.println( Arrays.toString( partsPhoneNum ));
        // Output:[203, 888765]
    }
}

 

3) How to split String in Java within a limit?

The Java String split() method provides it’s another variant with 2 arguments-
  • 1) Pattern
  • 2) Limit

“Limit” is an Optional Argument of the String split() Java method, as you already know that Java is an Object Oriented Programming language and perfectly supports the Polymorphism#MethodOverloading.

Example 3:
// Program: How to split a string in Java but limit the number of resulting parts?

import java.util.Arrays;

public class SecondSplitExample
{
    public static void main( String[] arguments)
    {
        String strPhoneNo = "203-8886-96655";                      // String containing dash or hyphens (-) 
        String[] allParts = strPhoneNo.split("-");                      // Splitting string by dash (-) 
        String[] limitedParts = strPhoneNo.split("-",2);          // Limiting the results to split till maximum 2 values

        System.out.println("All the Parts    : " + Arrays.toString( allParts ));
        System.out.println("Limited Parts: " + Arrays.toString( limitedParts ));

        /*      Output:
        All the Parts   : [203, 8886, 96655]
        Limited Parts : [203, 8886-96655]   
         */
    }
}

 

4) Java String split() by pipe “|”

Let’s assume, we have a String something like, strWithPipes = 12345|abcd|123numberText“; and we want all the substrings before and after the pipe | symbol. But when we call split(“|“)  passing the Pipe | symbol as a string, As a result, we will get all the characters of the string in the output- like below:

Example 4:
// Program: How to split a string by pipe "|" in Java

import java.util.Arrays;

public class SecondSplitExample
{
    public static void main( String[] arguments)
    {
        String strWithPipes = "12345|abcd|123numberText";
        String[] allParts = strWithPipes.split("|");            // Just regular string
        System.out.println( Arrays.toString( allParts ));
        /*
            Desired Output (3 elements):
                [
                    12345,
                    abcd,
                    123numberText
                ]
            Output Came (23 elements): 
                [1, 2, 3, 4, 5, |, a, b, c, d, |, 1, 2, 3, n, u, m, b, e, r, T, e, x, t]
        */
    }
}

 

To achieve the Desired output, we must have to use the double backslash \\ to escape the Pipe | symbol.

It’s because the String split() method always takes a regular expression, and the pipe | symbol is one of the special characters. It is used to perform the “OR” operation on its left and right side operands.

  • In the above String split() Java example, basically, we are splitting by ”OR”. That’s why, every time the result gets calculated by performing an OR operation based on its left and right side characters.
  • To get the desired results, we need two backslashes \\ because the first backslash \ will escape the second backslash \ in the string “\\|“, since the backslash \ is Java’s escape character in a string (that you may already know if ever used a new line character \n for printing a new line).
  • When we’ll write and run the above example with strWithPipes.split(“\\|“); Java will understand the string as \|, and further the Java regex engine will interpret it as a literal Pipe character |

Here is an example of Split() String by Pipe | in Java:

// Program: How to split a string by Pipe "|" in Java

import java.util.Arrays;

public class SecondSplitExample
{
    public static void main( String[] arguments)
    {
        String strWithPipes = "12345|abcd|123numberText";    // String with the Pipe '|' character
        String[] allParts = strWithPipes.split("\\|");                     // Escaped the Pipe '|' character with backslashes \\

        System.out.println( Arrays.toString( allParts ));
        /*
            Output Came == Desired Output (3 elements) :
                [
                    12345,
                    abcd,
                    123numberText
                ]
        */
    }
}

 

Note***
There are some special characters in Regular expression with some special meanings: the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the backslash \, the caret ^, the dollar sign $, the period or dot . , the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [ and the opening curly brace { . These special characters are often called “metacharacters“. You can check the full list here and here.

5) Split() string with . in Java?

The first try-
Most of the Java programmer firstly try the following approach when they need to split the String by dot . character:
String fileNameWithExtension = "HelloPlanet.java";
String theFileName = fileNameWithExtension.split(".")[0];        // Runtime Error
String theExtension = fileNameWithExtension.split(".")[1];        // Runtime Error

 

The above approach of splitting string by dot . will not work in Java because dot (.) is a special character in Regular Expression world and, it is used to match any single character not the literal dot . character (except the new line character).

Although, the above code will compile successfully, but you would not be able to run that program, as it will throw a runtime exception java.lang.ArrayIndexOutOfBoundsException. The split() method will return an empty array, and whenever you will try to access an array element using an index that doesn’t exist, you will get similar to this-:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SecondSplitExample.main(SecondSplitExample.java:10)

The problem with the above code is that dot “.” is a metacharacter and if you want to use it as a literal, you must have to escape it by using backslash just before the dot: \\.

  • To get the desired results, again we need two backslash \\ because the first backslash \ will escape the second backslash \ in the string “\\.” since the backslash \ is Java’s escape character in a string.
  • When we’ll write and run the above example replacing the fileNameWithExtension.split(“.“) with fileNameWithExtension.split(“\\.“) Java will understand this string as \. and the Java regex engine will interpret it as a single dot . character.

Here is the example of splitting a string using a . dot :

// 5th Example - How to split string by . in Java

import java.util.Arrays;

public class SecondSplitExample
{
    public static void main(String []arguments)
    {
        // String fileNameWithExtension = "HelloEarth.java";
        // String theFileName = fileNameWithExtension.split(".")[0];        // Runtime Error (Now you already know)
        // String theExtension = fileNameWithExtension.split(".")[1];        // Runtime Error

        // The correct way to split the file name and extension...

        String fileNameWithExtension = "HelloEarth.java";
        String theFileName = fileNameWithExtension.split("\\.")[0];
        String theExtension = fileNameWithExtension.split("\\.")[1];

        System.out.println("File Name With Extension : "+ fileNameWithExtension);
        System.out.println("File Name                : "+ theFileName);
        System.out.println("Extension                : "+ theExtension);

        /* OUTPUT: 
             -----------
             File Name With Extension : HelloEarth.java
             File Name                : HelloEarth
             Extension                : java          */ 
    }
}

 

What We Learned 

That’s String split Java tutorial. So far, we have learned, How to split string in Java. We have practically implemented all the Top 5 use cases of split(). We learned, how Regular expression and its metacharacters are used with the String split Java method.

In order to use split() efficiently, never forget one thing, and i.e. the String split() Java method always takes a regular expression. Also, to split on the basis of special characters (like- dot, pipe, star etc) we need to escape it by using two backslashes \\ one for Java and second one for Java regex engine (as explained above).

There are definitely some other useful mechanisms of splitting string in Java using Pattern class, Regex character classes and more. But we’ll learn them in another tutorial. For now, I hope you find this post helpful, Best of Luck with Java!!!

2 thoughts on “How to use split() in Java? String split() Java method”

Leave a Comment