0

Why java complains about

// int i;
if( i == null ){  }

and not about

// Integer i;
if( i == null ){  }

4 Answers 4

6

Because Integer is a reference type, and an int is not - that is, as int is not a pointer, it cannot point to nothing.

Sign up to request clarification or add additional context in comments.

Comments

2

int (primitive type) can't be null

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.