Search code examples
javanullprimitive

How can I check if a variable exists in Java?


I want to write to a variable only if there isn't anything already there. Here is my code so far.

if (inv[0] == null) {
    inv[0]=map.getTileId(tileX-1, tileY-1, 0);
}

It gives me this error:

java.lang.Error: Unresolved compilation problem: 
The operator == is undefined for the argument type(s) int, null

Solution

  • I'm assuming inv is an int[].

    There's no such concept as a value "existing" or not in an array. For example:

    int[] x = new int[5];
    

    has exactly the same contents as:

    int[] x = new int[5];
    x[3] = 0;
    

    Now if you used an Integer[] you could use a null value to indicate "unpopulated"... is that what you want?

    Arrays are always filled with the default value for the element type to start with - which is null in the case of reference types such as Integer.