First, we need to know the difference between pass-by-value and pass-by-reference.
Pass by value
- Pass-by-value is when you pass a variable as an argument for a function, the program will create a copy of this variable for the function to use. Therefore, no matter what happens inside the function, the variable will not change its value.
- Result
Pass by reference
- Opposite with Pass-by-value, when you pass a variable as an argument for a function, the program will throw it for the function to use. Therefore, if the function changes the argument’s value, the variable’s value will be changed too, because in this case, the variable and the argument are considered one.
- Result
- You can see the image to deeper understand:
How about in Java?
- Java is always pass-by-value!
- Maybe you are wondering: why when we pass an object parameter into a function, the value of this parameter will be changed?
What actually happens when we pass a non-primitive parameter into a function?
- First, we need to understand what a reference is in Java. For example, we declare a variable f that has Foo data type:
- This is what happens behind the scenes:
- The variable f which we always think is a real object in memory is actually not, it is just a reference to the object inside the memory cell.
- And in fact, when you pass a reference to a function, for example, we pass f in, the program will create another reference (let’s call it a) and link it to the same object that f points to, or in other words, it copies the reference f.
- Therefore, when we pass a variable f into a function:
public static void setAttribute(Foo f) {
f.setAttribute("c");
}
and when a function setAttribute job is done, reference a(cloned from f) disappears because out of the function, only f remains and the Foo object has been changed.
- Sound like Pass-by-reference, but actually not.