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?
The problem is
return n++;where n is returned and then only incremented. It works as expected if you change it toreturn ++n;orreturn n+1;But still what you are trying to test does not work with
Integerbecause it is immutable. You should try with something like –which is mutable.
Then you can pass around the reference to an instance of that class and mutate it (change the value of
valuein that instance) from the invoked method.Change the method –
and call it –