Can an int be null in Java?

No. Only object references can be null, not primitives.


int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!

e.g. this:

int a = object.getA(); // getA returns a null Integer

will give you a NullPointerException, despite object not being null!

To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>


A great way to find out:

public static void main(String args[]) {
    int i = null;
}

Try to compile.

Tags:

Java