DEV Community

Cover image for #26 Tricky questions in Arrays-JAVA
Deepikandas
Deepikandas

Posted on

#26 Tricky questions in Arrays-JAVA

1.Default values assigned
Arrays are the only objects even though inside method,default values are given


public class Arrays {
    public static void main(String[] value) {
        int[] arr = new int[3];
        System.out.println(arr[0] + " " + arr[1] + " " + arr[2]);
    }

}
Output:
0 0 0
Enter fullscreen mode Exit fullscreen mode

2.ArrayIndexOutOfBoundsException

public class Arrays {
    public static void main(String[] value) {
        int[] arr = new int[3];
        System.out.println(arr[3]);

    }

}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    at Module4/arrays.Arrays.main(Arrays.java:6)


Enter fullscreen mode Exit fullscreen mode

3.

4.Demonstrating Array Reference Behavior:

public class Arrays {
    public static void main(String[] value) {
        int[] a = {1, 2, 3};
        int[] b = a;
        b[0] = 100;
        System.out.println( "value of []a:"+a[0]);
    }

}
Output:
value of []a100
Enter fullscreen mode Exit fullscreen mode

5.a and b point to different array objects, even though they have the same elements

public class Arrays {
    public static void main(String[] value) {
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == b);
    }

}
output:
[I@65b3120a
[I@6f539caf
false

Enter fullscreen mode Exit fullscreen mode

6.NullPointerException


public class Arrays {
    public static void main(String[] value) {
        int[] arr = null;
        System.out.println(arr.length);
    }

}
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "arr" is null
    at Module4/arrays.Arrays.main(Arrays.java:6)
Enter fullscreen mode Exit fullscreen mode

7.NegativeArraySizeException


public class Arrays {
    public static void main(String[] value) {
        int[] arr = new int[-5];
    }

}
Exception in thread "main" java.lang.NegativeArraySizeException: -5
    at Module4/arrays.Arrays.main(Arrays.java:5)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)