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()
Course – LS – All
announcement - icon

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


res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.