Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

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 share the same character array. This 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 its various updates. 

One reason, which I could think of, 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 a bug and Oracle has fixed it, so no more substring memory leak issues in Java 7.

This issue doesn't undermine the importance of the substring method, which is one of the most useful methods from java.lang.String class.

 One more thing, which is also worth remembering is that, whenever you call the substring method, it returns a separate String object, because String is immutable in Java. In the next section, we will see the syntax of the substring method and How to use it for practical purposes.




SubString in Java - Description, Syntax, and Example

Substring 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 a couple of examples of substring methods 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 an empty String if you pass the length of String as a start in the first version and the 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 is two substring() method, first accept only starting point while second expect both starting and endpoints.
    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 the 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 a smaller String from a big text. We have also compared two overloaded versions of a substring by different substring examples, and also touched base on memory leak issue due to substring, which is now fixed in JDK 1.7.


Other Java Articles you may like:

If you have any questions or doubt about substring method or how to use in Java program, fee free to ask. 

Over to you now, when you create substring  in Java, a new String object is created, true or false? Can you also explain?

2 comments:

  1. All correct, all easy to grasp. Thanks
    JaiHind

    ReplyDelete
  2. Thank you , glad you find these examples useful

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.