In this Example we are going to change the Array into List and iterate the list.
Error Message :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4372)
at com.src.SumofSquares.main(SumofSquares.java:14)
Error Description :
package com.src;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SumofSquares {
public static void main(String[] args) {
int total = 0;
List<Integer> arr = Arrays.asList(1,2,3,4,0);
for(int i=7;i<=arr.size();i++) {
System.out.println(arr.get(i));
}
}
}
In the above program we get an error in the below code.
for(int i=7;i<=arr.size();i++), while iterating the iteration value (i) is more than the array Index size.so we will get ArrayIndexOutOfBound Exception.
Solution:
Instead of i<= arr.size() this we can use i< arr.size().
package com.src;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SumofSquares {
public static void main(String[] args) {
int total = 0;
List<Integer> arr = Arrays.asList(1,2,3,4,0);
for(int i=0;i<arr.size();i++) {
System.out.println(arr.get(i));
}
}
}
Output:
1
2
3
4
0
Post a comment
Please share your valuable feedback and share this article in social media.