Reputation: 117
I have a doubt in Java wrapper class like Integer
, Character
. I know that when we declare a class Abc
and can create an object to it in Java like
Abc a = new Abc();
It instantiates a with reference to Abc
class and in that we have fields that contain values for variables. My doubt being, when we create Integer
class like:
Integer i = 5;
How is it pointing to value 5
? Should not it contain a field which contains its value and point to Integer
object like:
static int value; // To hold value 5 for Integer class
Upvotes: 1
Views: 259
Reputation: 49606
How is it pointing to value 5?
It's pointing to an Integer
instance which holds that primitive value.
Integer i = Integer.valueOf(5);
which is a bit optimised version of new Integer(5)
(this one is deprecated since Java 9). The process is called autoboxing and is made by the compiler.
Should not it contain a field which contains its value?
It does contain a field. Though, it shouldn't be static and shared for the whole class.
private final int value;
Actually, Integer.valueOf(5)
will be taken from the cache as well as any value in the range [-128, 127]
unless a greater java.lang.Integer.IntegerCache.high
value is specified.
Upvotes: 1
Reputation: 3546
Integer i = 5;
from this, the compiler will make Integer i = Integer.valueOf(5);
(Autoboxing)
See also Oracle Docs in
Upvotes: 0
Reputation: 79828
To quote the Javadoc for Integer
An object of type Integer contains a single field whose type is int.
So yes, there is a field of type int
in the object returned by the autoboxing. The Integer
object returned by autoboxing might be
but it will be the same as the object returned by the static valueOf
method of the Integer
class.
The answers to this question may help you understand when valueOf
(and therefore autoboxing) creates a new object, and when it returns an existing object.
Upvotes: 1