When declaring this in a class:
Integer i = 9;
It complies now due to autoboxing I believe, is i
considered primitive data type?
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);
Yes it is autoboxed so i
will point to an Integer object with the value 9, not a primitive.
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.
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 convertsp
into a referencer
of class and typeInteger
, such thatr.intValue() == p
To show that i
is not a primitive variable just assign null
to it, that's not possible for primitive variables.
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.
i
is not a type, it is a variable