Java String.split()

The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.

We can also pass a limit to the number of elements in the returned array. If we pass 0 as a limit, then the method will behave as if we didn’t pass any limit, returning an array containing all elements that can be split using the passed delimiter.

Available Signatures


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



public void whenSplit_thenCorrect() {
    String s = "Welcome to Baeldung";
    String[] expected1 = new String[] { "Welcome", "to", "Baeldung" };
    String[] expected2 = new String[] { "Welcome", "to Baeldung" };

    assertArrayEquals(expected1, s.split(" "));
    assertArrayEquals(expected2, s.split(" ", 2));


* PatternSyntaxException – if the pattern of the delimiter is invalid.

@Test(expected = PatternSyntaxException.class)
public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() {
    String s = "Welcome*to Baeldung";

    String[] result = s.split("*");