When you declare Integer i = 9 in java, am I considered a primitive type because of autoboxing?

When declaring this in a class:

Integer i = 9;

      

This matches autoboxing now, I believe what i

counts as a primitive datatype?

+3


source to share


5 answers


No, the type i

is still Integer

(reference type) - what it declared after all. The fact that it is initialized with int

is completely decoupled from the type of the variable. The literal 9

is a value of the type int

, but it fits into the field Integer

.

The code is equivalent:



Integer i = Integer.valueOf(9);

      

+9


source


Yes, it is autoboxing, so it i

will point to an Integer with a value of 9, not a primitive.



+7


source


No, this is an instance of an object (link to). Due to autoboxing, primitive literal 9 is converted to instance Integer

and referenced i

.

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

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

If p is a type value int

, then the boxing conversion converts p

to a r

class reference and type Integer

, sor.intValue() == p

To show what is i

not a primitive variable, just assign to it null

, which is not possible for primitive variables.

+3


source


No, the type is i

not considered primitive: it is java.lang.Integer

, a wrapper type, autoboxed by the compiler.

What gives it a partial primitive look is the fact that Java puts small numbers, so you can compare them as if they were primitives:

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

      

Usually comparison for equality of values ​​with is ==

reserved for primitive types; you must use a.equals(b)

for referenced objects. However, the above expression also evaluates as true

because Java keeps an internal cache of small Integer

wrappers.

+2


source


Integer is a wrapper class for a primitive type int

, but with some some other functionality / methods, such as converting the same integer with a string. From the documentation :

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

Here you have a description of the wrapper classes.

+1


source







All Articles