0

I am new to Java and i wrote a simple program that calculates the sum of multiples of 3 below 10. I am not sure why i am getting Array Out Of Bounds Exception

int a[] = {},j = 0,sum = 0;
        for(int i=1;i<=10;i++)
        {
            if ((i % 3) == 0)
            {
            a[j] = i; // Here, i am getting the exception
            j++;
            }
        }
        for(int i1=0;i1<j;i1++)
        {
            sum = sum + a[i1];
        }
        System.out.println(sum);
     }
4
  • 2
    Define array size of a. Commented Apr 9, 2016 at 3:05
  • 1
    Arrays are static. Since you defined it as having 0 values in int a[] = {}, you will get an outOfBoundsException by trying to set a value of any index in the array. You will need to either set the values of the array or set a size for the array (in which case all positions will be automatically filled with 0). Commented Apr 9, 2016 at 3:06
  • Thank You very much. I believe it was too silly for this forum Commented Apr 9, 2016 at 3:09
  • 1
    Declare an array with size...it will stop crashing. Commented Apr 9, 2016 at 3:13

1 Answer 1

2

Here's the solution. You were just missing defining the size of the array. Hope it helps :).

public final class Program {

public static void main(String[] args) {

    int a[] = new int[10] , j = 0, sum = 0;
    for (int i = 1; i <= 10; i++) {
        if ((i % 3) == 0) {
            a[j] = i; // Here, i am getting the exception
            j++;
        }
    }
    for (int i1 = 0; i1 < j; i1++) {
        sum = sum + a[i1];
    }
    System.out.println(sum);
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.