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

Array declaration creation1641
What will be the output of the following program?
`public class Test {    public static void main(String[] args) {        int[] arg = {5, 0, 2, 3, 1, 4};        int length = arg.length;        int[] array = new int[length];        for (int i = 0; i < length; i++)            array[i] = arg[i];        boolean[] exists = new boolean[length];        for (int i = 0; i < length; i++) {            if (array[i] < 0 || array[i] >= length || exists[array[i]])                throw new RuntimeException("Input is not a per.");            exists[array[i]] = true;        }        int[] ainv = new int[length];        for (int i = 0; i < length; i++)            ainv[array[i]] = i;        for (int i = 0; i < length; i++)            System.out.print(ainv[i] + " ");        System.out.println();    }}`

 A. 4 1 3 2 0 5 B. 1 4 2 3 5 0 C. 1 4 3 2 5 0 D. Some other output E. Compilation Error or Runtime Error
Topic:

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

ans : e
exist[] not initialized...so can't use it before initialize

Posted by Ananda Kumar    2014-04-21 12:40:07

ans is b bcz in second for loop exists[] is kept true then anv[5]=0, anv[0]=1, anv[2]=2, anv[3]=3, anv[1]=4, anv[4]=5
so prints 1,4,2,3,5,0

Posted by Pooja Singh    2014-04-21 12:55:02

Answer is B. We have first initialized array with the elements of arg. Then in the for loop, if statement ensures that the elements of array are not negative, not greater than or equal to the length of the array and not duplicate. The entries in the boolean array are changed to true accordingly. Then ainv array contains elements from 0 to 5 at the locations of elements in the "array".

Posted by Shaileshwar Sharma    2014-04-21 13:03:11

Congratulations Pooja Singh. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-04-22 04:20:35