ArticleJavaString

Java String substring() Method

substring in Java

Often programmers need to extract substrings from String objects in Java. It’s possible by the String class substring() method.

As we had written before the substring() methods are the part or String class where objects are immutable. Further in this article, we will dig into the internal structure of the substring() method with all related aspects.

How to Extract a Substring of String in Java

The main functionality is represented by two methods, see them below.

  • public String substring(int startIndex) – extracting whole string after start index    
  • public String substring(int startIndex, int endIndex) –  extracts only substring from start till the end index.

What is About Immutability of Substrings?

As we can see from the internal code of the String class substring() method uses a specific new String constructor. See please code below.

return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); 

It means that every time when we try to extract a substring new object in memory is created. And we should be very careful in order when especially working with long strings.

What Happens When We are Out of the Index in Substring Params?

The general answer is that a specific exception occurs. As we can see from the internal code it is StringIndexOutOfBoundsException. See please examples below.

if (beginIndex < 0)   
  throw new StringIndexOutOfBoundsException(beginIndex);  
  
if (endIndex > value.length)   
  throw new StringIndexOutOfBoundsException(endIndex);    

Conclusion

Hi, I’m Vlad

Leave a Reply