I'm developing an java application and now I noted an a strange behaviour that confused me. I have the following situation:
Integer currentIndex = 0;
doSomethings(currentIndex);
System.out.println("Print "+currentIndex);
private void doSomethings(Integer currentIndex){
//Do other things and update my current index
currentIndex++;
}
but I get always 0 like value. I remember that the objects are passed like reference in java, while the primitive types like copy. Why Do I get 0 in this case?
Instance of Integer
is immutable. It means you cannot change its value. When you increase it by one, Integer
gets converted into int
(this is called "unboxing"), then this int
gets increased by one. You can even cast it back to Integer
. But this will be already another instance of Integer
, not the one you've passed to the method. That's why your original reference stays equal to zero all the time.
Byte code :
private static void doSomethings(java.lang.Integer);
Code:
Stack=2, Locals=1, Args_size=1
0: aload_0
1: invokevirtual #56; //Method java/lang/Integer.intValue:()I --> get the int value of the Integer
4: iconst_1 --> constant value 1
5: iadd --> add int value and 1
6: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/In --> get another integer with value increased by 1
teger;
9: astore_0
10: return
This is an interesting construct.
Note that Objects in Java don't allow custom operator implementations. And that the ++ operator is not defined for a java Object.
So java will do a trick that is call 'auto boxing'. This converts Integer
to int
and vice versa when needed.
What happens when you do:
Interger myInt = 0;
int i = myInt++; // this line
is as follows:
myInt
will be converted to int
, then that int value is incremented and store in i
. Note that the integer value is not saved to myInt
.
This is what happens in your function, the ++
only happens in a temporary variable, not in the actual Integer
object. Note that because the Integer
object is immutable, this is not even possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With