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.
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.
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.
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
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.