Possible Duplicate:
Is Java pass-by-reference?
Java pass by reference
For the following Java program, my understanding is that a is a reference type to an Integer, like pointer type in C/C++. So any changes done in method f to its value will be reflected after the method returns. But println still prints its original value 0 instead of 3.
Integer and int does not make a difference. Was my previous understanding wrong? Please help. Thank you!
public static void f(Integer b){
b=3;
}
public static void main(String[] args){
Integer a=0;
f(a);
System.out.println(a);
}
Integer(like other “basic” classes) are inmutable objects. It means that there is no method by which you can change the value. If you dothe object created will always hold the 1 value.
Of course you can do
but here what you are doing is creating two objects, and assigning a to each of them in turn.
When calling the method, you are passing a copy of the reference in
a(as edalorzo said), so you are doing pretty much the same (but without changing the originalareference).Of course, lots of classes are not inmutable. In these classes, you would have one (or several) methods that allow you to change the object inner state, and (as long as you are accessing the same object) these changes would be “shared” by all the references of the object (since they all point to the same one). For example, suppose Integer had a
setValue(int)method, thenWould work as you expected.