Java array index of 4
I'm new to Java and running under code that works fine, but I am getting the array index from the associated exception. Can someone please help to understand why I am getting this exception?
public class array {
public static void main (String[] args)
{
int[] b = {1,2,3,4};
array ar = new array();
ar.process(b);
}
public int process (int[] a)
{
int i;
System.out.println("Length is: " +a.length);
for(i = 0; i < a.length ; i++) {
System.out.println("A is : " + a[i] + " I is" +i);
}
return a[i];
}
}
Exception
Length is: 4
A is : 1 I is0
A is : 2 I is1
A is : 3 I is2
A is : 4 I is3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at array.process(array.java:17)
at array.main(array.java:7)
source to share
When the return statement is executed, the for loop is complete, so it i
is equal to the length of the array a
(which is one valid index). Modify the return statement like
return a[a.length - 1]; // <-- for the last element in the array.
Of course, you don't use the return value to simply invalidate the method and return nothing. You can also make the method static since you don't use any instance fields (then you don't need an instance array
... Java's naming convention would be to use class names, but don't name your class array
).
source to share
If you are expecting the last value as a return value, you cannot use it i
as an array index, because in the for loop when the value i
becomes 4
ie i == a.lenth
for the loop brakes. you cannot access an element with an index equal to the length of the array.
Modified code:
public class array {
public static void main (String[] args)
{
int[] b = {1,2,3,4};
array ar = new array();
ar.process(b);
}
public int process (int[] a)
{
int i;
System.out.println("Length is: " +a.length);
for(i = 0; i < a.length ; i++) {
System.out.println("A is : " + a[i] + " I is" +i);
}
return a[a.lenght-1]; // if you want last element as return value
}
}
source to share