info@meritcampus.com    +91-85006-22255
...
`

Calculate sum
What will be the output of the following program?
`public class FindSum {    public static void main(String[] args)     {        int[] a = {12, 15, 11, 13, 9, 25};        int[] a2 = {12, 15, 11, 13, 9, 25};        int sum = 0;        for (int i = 0; i < a.length; i++)         {            if (a[i] % 3 == a2[a.length - i] % 5)             {                sum += i * i;            }        }        System.out.println("sum = " + sum);    }}`

 A. sum = 5 B. sum = 25 C. sum = 30 D. Compilation Error E. Throws ArrayIndexOutOfBoundsException
Topic:

### User comments below.All of them might not be correct.

ANS IS E (Throws ArrayOutOfBoundsExcption)

--Here hte concept of "ARRAYS" is used.

--Execution starts from main()
Two integer arrays a and a2 are declared with 6 elements as follows:
12
15
11
13
9
25

length of both the arrays is 6,but as array is 0 indexed so first element will be havind index as zero and last element will be having index as 5.

--For loop is written next which runs till the length of array a i.e. 6 times.
Inside for loop if condition ise used as follows
a[i]%3 i.e. a[0]%3 i.e. 12%3 ---> 0 = a2[a.length-i] i.e a2[6-0] i.e. a2[6]%5.Here Exception will be thrown which says Throws ArrayOutOfBoundsExcption as 6th element is not there in array of length 5.so,ArrayOutOfBoundsExcption will be thrown.

OUTPUT:
Throws ArrayOutOfBoundsExcption

Posted by Mânïshå Mùlchåndânï    2015-02-17 09:01:04

ans e.  runtime exception  ArrayIndexOutOfBoundsExcption ...initially 2 arrays initialized with 6 elements. a[0]=12,a[1]=15,a[2]=11,a[3]=13,a[4]=9,a[5]=25.array indexes are always started from 0.thn sum is initialized with 0. here for loop is used to access array elements.for loop iterates upto condition reached length of array.for i=0,if(a[0]%3==a2[6-0]%5) ==if(0==unreferenced element) bcz a[6] is not present in given array,it has 0 to 5 index .here we are trying to access unreferenced element so  ArrayIndexOutOfBoundsExcption  get thrown.. If we request for an index that is either negative, or greater than or equal to the size of the array, an ArrayIndexOutOfBoundsExceptionis thrown.  The ArrayIndexOutOfBoundsException is a RuntimeException thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.

Posted by Maheshwari Natarajan    2015-02-17 13:21:01

e

Posted by Shubham Bansal    2015-02-17 17:10:59

This dose is now closed and the winners are Mânïshå Mùlchåndânï,  for 'First Correct Comment', Mânïshå Mùlchåndânï,  for 'Best Comment' and Mânïshå Mùlchåndânï for the 'Popular Comment'. The 'lucky liker' is Maheshwari Natarajan. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-02-18 03:42:06