Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an int be null in Java?

Tags:

java

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>


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


A great way to find out:

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

Try to compile.


In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.

The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.

This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.


Along with all above answer i would like to add this point too.

For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.

So by default we have,

   int a=0;

and not

   int a=null;

Same with other primitive types and hence null is only used for objects and not for primitive types.