java.lang.StringIndexOutOfBoundsException while iterating a String in Java


In this Example we are going to convert int  to int Array in Java

Error Message :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 3, end 4, length 3
       at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
       at java.base/java.lang.String.substring(String.java:1883)
       at com.src.ArrayDititsSum.convertArray(ArrayDititsSum.java:15)
       at com.src.ArrayDititsSum.main(ArrayDititsSum.java:7)

Error Description :


package com.src;

public class ArrayDititsSum {

       public static void main(String[] args) {
             
              convertArray(963);
       }
       public static void convertArray(int num)  {
           String str = Integer.toString(num);
           String temp;
           int temp1;
           int [] intArray = new int[str.length()];
           for(int i=0;i<=str.length();i++) {
                   temp = str.substring(i, i+1);
               temp1 =  Integer.parseInt(temp);   
               intArray[i] = temp1;
           }
                   for(int i=0;i<=intArray.length;i++) {
                       System.out.println(intArray[i]);
                   }  
       }
}

In the above program we get an error in the below code.
for(int i=0;i<=str.length();i++) while iterating, the iteration value (i) is more than the string Index size.so we will get StringIndexOutOfBoundException.


Error Solution:

Instead of i<= str.length() this we can use ii<= str.length()
package com.src;

public class ArrayDititsSum {

       public static void main(String[] args) {
             
              convertArray(963);
       }
       public static void convertArray(int num)  {
           String str = Integer.toString(num);
           String temp;
           int temp1;
           int [] intArray = new int[str.length()];
           for(int i=0;i<str.length();i++) {
                   temp = str.substring(i, i+1);
               temp1 =  Integer.parseInt(temp);   
               intArray[i] = temp1;
           }
                   for(int i=0;i<intArray.length;i++) {
                       System.out.println(intArray[i]);
                   }  
       }
}


Output:
9
6
3     


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