In this Example we are going to understand the exceptions while parsing the string to int.
Here we will get String Index out of range exceptions .
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 example due to the red background color code we are getting the error String out of bound Exception.
While iteration the iteration value starts from 0 and it will iterate more then the string length (4 ) but the string length is 3 so this exception will occur.
Solution:
We need to change the iteration less than to the string length. So we changed the code like green background code shown below.
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
Post a comment
Please share your valuable feedback and share this article in social media.