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)


public void whenCallSubstring_thenCorrect() {
    String s = "Welcome to Baeldung";
    assertEquals("Welcome", s.substring(0, 7));


  • 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 »
Java String.toLowerCase()
« Previous
Java String.subSequence()
Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!