{ int == nulltype } vs. { Integer == nulltype }
Why java complains abou开发者_StackOverflow中文版t
// int i;
if( i == null ){ }
and not about
// Integer i;
if( i == null ){ }
Because Integer is a reference type, and an int
is not - that is, as int
is not a pointer, it cannot point to nothing.
int (primitive type) can't be null
Because int
is a primitive type , while Integer
is its wrapper class .
Said differently, int
is a value type (and as such cannot be null
) while Integer
is a reference type (and as such can be null
).
In Java, every primitive type (such as boolean
, double
or char
) is a value type. Since primitive types do not inherit from Object
, a set of "wrapper classes" is offered (Boolean
, Double
, Character
to name a few) when such behavior is needed (like, for instance, putting them in containers, or using them as generic type parameters).
The result is that primitive types really are second class citizens in Java.
Because int is a value type and it cannot be null - it's the object itself. Integer, on the other hand, is a reference type and can be null or hold a reference to an object.
精彩评论