How to check null element if it is integer array in Java?

arrays, int, java, null

Solution

In Java, an `int` is a primitive type and cannot be `null`. Objects, however, are stored as references, so if you declare an object reference but do not make a `new` object, the reference will be `null`.

`Integers` are object wrappers around `ints`, meaning they can be `null`.

public void test() {
        Integer[] a = new Integer[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //should now compile
                System.out.println('null!');
            }
        }
    }

Problem

I'm quite new to Java and having an issue checking null element in integer array. I'm using Eclipse for editor and the line that checks null element is showing error: Line that complains: ``` if(a[i] != null) { ``` Error msg from Eclipse: ``` The operator != is undefined for the argument type(s) int, null ``` In PHP, this works without any problem but in Java it seems like I have to change the array type from integer to Object to make the line not complain (like below) ``` Object[] a = new Object[3]; ``` So my question is if I still want to declare as integer array and still want to check null, what is the syntax for it? Code: ``` public void test() { int[] a = new int[3]; for(int i=0; i<a.length; i++) { if(a[i] != null) { //this line complains... System.out.println('null!'); } } } ```

Original source

Related problems