0

Hi I read this question on Stack overflow, and tried to do an example.

I had the below code:

public static void main(String[] args){
     int i = 5;
     Integer I = new Integer(5);

     increasePrimitive(i);
     increaseObject(I);

     System.out.println(i); //Prints 5 - correct
     System.out.println(I); //Still prints 5
     System.out.println(increaseObject2(I)); //Still prints 5

}

public static void increasePrimitive(int n){
     n++;
}

public static void increaseObject(Integer n){
     n++;
}

public static int increaseObject2(Integer n){
         return n++; 
}

Does the increaseObject print 5 because the value of reference is changing inside that function? Am I right? I am confused why the increasedObject2 prints 5 and not 6.

Can anyone please explain?

Community
  • 1
  • 1
rgamber
  • 5,231
  • 8
  • 48
  • 92
  • did you mean to use `increaseObject(I);`? (note the `I` instead of `i`) – lccarrasco Oct 03 '12 at 03:35
  • 1
    Integer is immutable in Java. Similar topic: http://stackoverflow.com/questions/5560176/java-is-integer-immutable – Alex Oct 03 '12 at 03:37
  • @Alexey, then what is happening with the `increaseObject` method in this case, considering that Integer is immutable? – rgamber Oct 03 '12 at 03:41
  • You can change this way: n = n+1. Here is exactly the same question: http://stackoverflow.com/questions/2208943/how-to-increment-a-class-integer-references-value-in-java-from-another-method – Alex Oct 03 '12 at 03:45

2 Answers2

1

In increasedObject2() function,

return n++;

It is postfix. So after n = 5 has been return, it increases n value, i.e n=6.

swemon
  • 5,474
  • 4
  • 29
  • 53
1

The problem is return n++; where n is returned and then only incremented. It works as expected if you change it to return ++n; or return n+1;

But still what you are trying to test does not work with Integer because it is immutable. You should try with something like -

class MyInteger {
     public int value; //this is just for testing, usually it should be private

     public MyInteger(int value) {
         this.value = value;
     }
}

which is mutable.

Then you can pass around the reference to an instance of that class and mutate it (change the value of value in that instance) from the invoked method.

Change the method -

public static void increaseObject(MyInteger n){
     n.value++;
}

and call it -

MyInteger i = new MyInteger(5);    
increaseObject(i);
Bhesh Gurung
  • 48,464
  • 20
  • 87
  • 139