Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referenced Integer object not incremented

Tags:

java

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?

like image 472
Skizzo Avatar asked Dec 15 '22 19:12

Skizzo


2 Answers

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
like image 164
sergej shafarenka Avatar answered Jan 02 '23 00:01

sergej shafarenka


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.

like image 38
Thirler Avatar answered Jan 02 '23 00:01

Thirler