java.lang.StringIndexOutOfBoundsException in substring of String in java


In this Example we are going to understand the exceptions while using the substring value

Error Message :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 9, end 12, length 11
       at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
       at java.base/java.lang.String.substring(String.java:1883)
       at com.si.SimpleJavaPro.main(SimpleJavaPro.java:7)
Error Description :


package com.si;

public class SimpleJavaPro {

       public static void main(String[] args) {
              String str = "Hello World";
              if(str.substring(9  , 12).equals("World")) {
                     System.out.println(str.substring(9      , 12));
              }
       }
}

In the above example ,the red background color line is giving the exception.
The substring endindex value is greater than the string length value .thats why we got this exception.

Solution:

To avoid this exception we need restrict the endindex value as String length.

package com.si;

public class SimpleJavaPro {

       public static void main(String[] args) {
              String str = "Hello World";
              if(str.substring(6  , str.length()).equals("World")) {
                     System.out.println(str.substring(6      , str.length()));
              }
       }
}

                         
Output:
World

Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar