Java-passes-by-reference-Or-by-value
This is a classic question of Java. Many similar questions have been asked on stackoverflow, and there are a lot of incorrect/incomplete answers. The question is simple if you don’t think too much. But it could be very confusing, if you give more thought to it.
1. A code fragment that is interesting & confusing
1 | public static void main(String[] args) { |
It prints “ab”.
2.What the code really does?
When the string “ab” is created, Java allocates the amount of memory required to store the string object. Then, the object is assigned to variable x, the variable is actually assigned a reference to the object. This reference is the address of the memory location where the object is stored.
The variable x contains a reference to the string object. x is not a reference itself! It is a variable that stores a reference(memory address).
Java is pass-by-value ONLY. When x is passed to the change() method, a copy of value of x (a reference) is passed. The method change() creates another object “cd” and it has a different reference. It is the variable x that changes its reference(to “cd”), not the reference itself.
The following diagram shows what it really does.
3. conclusion
Java is always pass-by-value. Primitive data types and object reference are just values.
4. one more question
why the member value of the object can get changed?
here is the code :
1 | class Apple { |
Since the orignal and copied reference refer the same object, the member value gets changed.
a same phenomenon will be found in collection situation
.