Which method in a wrapper class is called when boxing a primitive in Java

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

I am sure that this is not a constructor, it may be the valueOf() method.

+4
source share
3 answers

Yes, this value is Of:

Here's the javap output:

 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 
+6
source

This Integer.valueOf(int) similar for Boolean, Byte, Character, Long, Float and Double.

Note: for booleans and bytes, all possible values ​​are cached. For characters, values ​​0 through 127 are cached. For short and long values, -128 - 127 are cached. For Integer -128 - 127 are cached by default, but the maximum can be increased using several parameters.

This can lead to unexpected behavior with

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

prints

 true false 

Not sure if you need to do -128 using (int) -128 to compile in Java 7.

+6
source

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

And especially for integers in the range -128, 127, you will never see the constructor called when using valueOf , because Integer has these cached instances.

+4
source

All Articles