4

Which method in the Integer class will be used when you do Integer i = 1;

I'm pretty sure that it's not the constructor, it might be the valueOf() method.

Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
Stijn Vanpoucke
  • 1,425
  • 3
  • 17
  • 30
  • Possible duplicate of [What code does the compiler generate for autoboxing?](http://stackoverflow.com/q/408661/851811) – Xavi López Oct 26 '11 at 08:04

3 Answers3

5

It is Integer.valueOf(int) similarly for Boolean, Byte, Character, Long, Float and Double.

Note: for Boolean and Byte all possible values are cached. For Character, the values 0 to 127 are cached. For Short and Long values -128 to 127 are cached. For Integer -128 to 127 are cached by default, however the maximum can increase using a number of options.

This can lead to surprising behaviour with

System.out.println((Integer) (int) -128 == (Integer) (int) -128);
System.out.println((Integer) (int) -129 == (Integer) (int) -129);

prints

true
false

Not sure what you need to cast -128 with (int) -128 for this to compile in Java 7.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I was looking into the Integer source for the cache stuff, that's why I was wondering with method was used while boxing because the constructor doesn't use the '+-127 cache'. – Stijn Vanpoucke Oct 26 '11 at 08:27
  • The constructor has to create a new object every time, it has no choice. One of my pet hates is people using `new Boolean(flag)` ;) – Peter Lawrey Oct 26 '11 at 08:29
5

Yes, it's valueOf:

Here's the output of javap:

public static void main(java.lang.String[]);
  Code:
   Stack=1, Locals=2, Args_size=1
   0:   iconst_1
   1:   invokestatic    #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   4:   astore_1
   5:   return
  LineNumberTable:
   line 5: 0
   line 6: 5
Tarlog
  • 10,024
  • 2
  • 43
  • 67
3

It actually is valueOf(). Take a look at this possible duplicate question: What code does the compiler generate for autoboxing?.

And particulary for integers in the range -128, 127, you'll never see the constructor invoked when using valueOf because Integer has these instances cached.

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161