1

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
Andrew Tobilko
  • 44,067
  • 12
  • 74
  • 128

3 Answers3

1

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.

Dawood ibn Kareem
  • 68,796
  • 13
  • 85
  • 101
1

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.

Andrew Tobilko
  • 44,067
  • 12
  • 74
  • 128
  • Sir, Are not final variables supposed to be initialized in constructors or non-static initializers only? – Handmadegifts co Mar 13 '18 at 17:56
  • @Handmadegiftsco, yes, they are. But a static method could call a constructor or refer to another static member (have a look at `static final Integer cache[]` inside `private static class IntegerCache`) – Andrew Tobilko Mar 13 '18 at 18:08
0
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

Bruno Carletti
  • 246
  • 3
  • 18
kerner1000
  • 2,661
  • 28
  • 46