4

When declaring this in a class:

Integer i = 9;

It complies now due to autoboxing I believe, is i considered primitive data type?

2
  • No. It's an object.
    – Maroun
    Jan 1, 2015 at 19:27
  • 1
    i is not a type, it is a variable Jan 1, 2015 at 19:28

5 Answers 5

10

No, the type of i is still Integer (the reference type) - that's how it's declared, after all. The fact that it happens to be initialized using an int is entirely separate from the type of the variable. The literal 9 is a value of type int, but it's boxed into an Integer.

The code is equivalent to:

Integer i = Integer.valueOf(9);
7

Yes it is autoboxed so i will point to an Integer object with the value 9, not a primitive.

0
3

No, i's type is not considered primitive: it is java.lang.Integer, a wrapper type, autoboxed by the compiler.

What gives it a partial appearance of a primitive is the fact that Java interns small integers, so you can compare them as if they were primitives:

Integer a = 9;
Integer b = 9;
if (a == b) { // This evaluates to true
    ...
}

Normally, comparison for value equality with == is reserved for primitive types; you should use a.equals(b) for reference objects. However, the expression above also evaluates to true, because Java keeps an internal cache of small Integer wrappers.

3

No, it's a (reference to an) object instance. Due to autoboxing the primitive literal 9 is converted to an Integer instance and referred to by i.

See 5.1.7. Boxing Conversion of the Java Language Specification (JLS):

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type... At run time, boxing conversion proceeds as follows:

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

To show that i is not a primitive variable just assign null to it, that's not possible for primitive variables.

0
1

Integer is a wrapper class for the primitive type int, but with some little other features/methods, such as converting the same integer to a string. From the documentation you have:

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

Here you have a description of the Java wrapper classes.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.