I just announced the new Spring 5 modules in REST With Spring:


This article is part of a series:
• Java String.String()
• Java String.substring()
• Java String.codePointCount()
• Java String.codePointAt()
• Java String.concat()
• Java String.contains()
• Java String.copyValueOf()
• Java String.endsWith()
• Java String.format()
• Java String.getBytes()
• Java String.indexOf()
• Java String.intern()
• Java String.isEmpty()
• Java String.lastIndexOf()
• Java String.regionMatches()
• Java String.replace()
• Java String.replaceAll()
• Java String.split()
• Java String.startsWith()
• Java String.subSequence()
• Java String.substring()
• Java String.toLowerCase()
• Java String.toUpperCase()
• Java String.trim()
• Java String.valueOf()

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);

I just announced the new Spring 5 modules in REST With Spring: