5 Examples of substring() in Java

SubString in Java is a useful method from java.lang.String class, which is used to create smaller String from bigger ones. The way Substring works prior to Java 1.7 can create a subtle memory leak because both String and their substring shares same character array. Which means, if you have a big String of 200MB and created a substring of 2MB from that, that could prevent 200MB String from being garbage collected. I agree this doesn't look normal and indeed was a bug, but it was like that till Java 1.6 and it's various update. One reason, which I could think, why Java designer initially thought like that, maybe to save memory by sharing char array and to make, creating substring faster by just copying pointers, instead of data. Nevertheless, this was reported as bug and Oracle have fixed it, so no more substring memory leak issue in Java 7.


This issue doesn't undermine the importance of substring method, which is one of the most useful methods from java.lang.String class. One thing, which is also worth remembering is that, whenever you call substring method, it return a separate String object, because String is immutable in Java. In next section, we will see the syntax of substring method and How to use it for practical purpose.




SubString in Java - Description, Syntax and Example

Substring Example in JavaSubstring method is overloaded in Java, and we have two variants of it, first accept one parameter, just begin index and second accept two parameters, begin index and end index as shown below:

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


In the case of the first method, substring starts with beginIndex and goes till the end of String, while, in the case of an overloaded  method, substring starts from beginIndex and goes till endIndex -1. Since String in Java is zero indexes based,  beginIndex can be from 0 to length of String. Let's see couple of examples of substring method to learn how they work:

public class SubStringTest {

    public static void main(String[] args) {

    String quote = "Java is to JavaScript what Car is to Carpet";     
                                                                    
 // Example 1 - Let's say, we need only "what Car is to Carpet" substring       
 // out start will be 22, you can also do quote.indexOf("what")     
 // and we can first substring method                               
                                                                    
 String substr = quote.substring(22);                               
 System.out.println(substr);                                        
                                                                    
 // Example 2 - Let's say, we need "Java" from quote                            
 // start will be 0 and end will be 4 (because end is exclusive)    
                                                                    
 String substr2 = quote.substring(0,4);                             
 System.out.println(substr2);                                       
                                                                    
 // Example 3 - Following call to substring method will return empty String   
 String substr3 = quote.substring(quote.length());                  
 System.out.println(substr3.isEmpty());                             
                                                                    
 // Example 4 - substring method will also return empty String if begin = end   
 String substr4 = quote.substring(3,3);                             
 System.out.println(substr4.isEmpty());                             
                                                                    
 // Example 5 - This substring call will throw IndexOutOfBoundException         
 String substr5 = quote.substring(-1);  // start < 0                
 String substr6 = quote.substring(2,1); // start > end              
  
    }

}
Output 
what Car is to Carpet
Java
true
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
 at java.lang.String.substring(Unknown Source)
 at java.lang.String.substring(Unknown Source)
 
Remember substring(int beginIndex) method will throw IndexOutOfBoundException if, an index is less than zero or more than length of String. While substring(int beginIndex, int endIndex) will throw IndexOutOfBoundException if beginIndex is negative, or larger than endIndex or end > length().

It's also worth knowing that substring will return empty String if you pass the length of String as a start in the first version and same index as start and end in the second method, as shown in our substring example in Java.


Important points about substring() in Java

  1. There are two substring() method, first accept only starting point while second expect both starting and end points.
    public String substring(int beginIndex)
    public String substring(int beginIndex, int endIndex)
  2. The string starts with index 0 i.e. first character will be at index 0. So if you want to remove the first character, just do substring(1), it will return substring without first character, equal to deleting the first character.
  3. In the second method, startIndex is inclusive but endIndex is exclusive, which means if you want to remove the last character then you need to give substring(0, string.length()-1).
  4. The substring() method will return an empty String if beginIndex= endIndex.
  5. The substring() method will throw IndexOutOfBoundsException if start < 0 or start > end.
and here is a nice summary slide of all the important things you learned about the substring() method in this article by doing those examples:

10 Examples of substring in Java




That's all about substring in Java. we have seen How to use substring to create smaller String from a big text. We have also compared two overloaded version of substring by different substring examples, and also touched based on memory leak issue due to substring, which is now fixed in JDK 1.7.


Further Reading
Java Programming Interview Exposed
How to reverse String without StringBuffer in Java
How to use String matches method in Java with Regular Expression
Java String trim() Example to remove white spaces
Java String indexOf() example
How to split String by comma in Java
Difference between String and StringBuffer in Java
Core Java, Volume 1 9th Edition by Cay S. Horstmann



No comments:

Post a Comment