Reference and Value confusion
Posted
by
rgamber
on Stack Overflow
See other posts from Stack Overflow
or by rgamber
Published on 2012-10-03T03:31:15Z
Indexed on
2012/10/03
3:37 UTC
Read the original article
Hit count: 118
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?
© Stack Overflow or respective owner