简体   繁体   中英

Java Wrapper class reference pointing to a primitive value

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

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

  • newly created, or
  • returned from a cache;

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.

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.

Integer i = 5;

from this, the compiler will make Integer i = Integer.valueOf(5); (Autoboxing)

See also Oracle Docs in

Autoboxing and Unboxing

The Numbers Classes

Immutable Objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM