3

I am new to Java and was running below code which runs fine but I get an array index out of bound exception. Can someone please help understand why am I 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)
codeninja
  • 79
  • 9

3 Answers3

3

Problem is this line:

return a[i];

Since it is outside for loop and i has become 4.

You can make it:

return a[i-1];

to fix it, but you need to clarify why you're returning last element of an array as return value.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

When your return statement runs, the for loop has finished so i is equal to the array a length (which is one past a valid index). Change the return statement like

return a[a.length - 1]; // <-- for the last element in the array.

Of course, you aren't using the returned value so you could just make the method void and return nothing. You could also make the method static since you aren't using any instance fields (then you wouldn't need an instance of array... Java naming convention would be to capitalize class names, but please don't name your class Array).

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

If you are expecting last value as your return value, then you cannot use i as array index because in for loop when i value become 4 i.e i == a.lenth for loop execution brakes. you can not access element that having index equal to array length..

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
    }        
    }
atish shimpi
  • 4,873
  • 2
  • 32
  • 50
  • Thanks a lot guys for explaining the issue. Changing return statement to (return a[i] - 1) worked for me. – codeninja Dec 13 '14 at 16:56