Java String.substring()

The method substring() comes with two signatures. If we pass the
beginIndex and the endIndex to the method, then it obtains a part of a
String given the starting index and the length of the result.

We can also pass the beginIndex only and obtain the part of the String
from the beginIndex to the end of the String.

Available Signatures

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

Example

@Test
public void whenCallSubstring_thenCorrect() {
    String s = "Welcome to Baeldung";

    assertEquals("Welcome", s.substring(0, 7));
}

Throws

  • IndexOutOfBoundsException – if the first index is negative, the
    first index is larger than the second index or the second index is
    larger than the length of the String

@Test(expected = IndexOutOfBoundsException.class)
public void whenSecondIndexEqualToLengthOfString_thenCorrect() {
    String s = "Welcome to Baeldung";

    String sub = s.substring(0, 20);
}

Next »

« Previous

Leave a Reply

Your email address will not be published.