Many students always question the transfer of parameters in Java programming, in the end is to pass the value or pass the reference? Always ambiguous, leading to programming involved in this aspect is very distressed, on this issue, I am here to describe my understanding, welcome to criticize.
First lock a fundamental direction: in Java, only the value is passed!
Here is a classmate wondering, only to pass the value of the reference to the argument why? To facilitate understanding, we can say this:
In Java, simple data types are passed by value, and objects are passed by reference ... Halo, this person how to speak Topsy-Turvy, Tang's monk .... Haha, don't worry, listen to me slowly ....
1. The so-called transfer value, the pressure stack is a copy of the parameter values, is to assign the value of the actual parameters to the formal parameters, any modification of the formal parameters will not affect the value of the argument;
2. And the reference (similar to the pointer in C), the stack is a copy of the reference, is the way to address the transfer of parameters, after delivery, formal parameters and arguments are pointing to the same object, but their names may be different, changes to formal parameters will affect the value of the argument.
Attentive spectators should be aware, the top 2nd, the reference copy itself is also passed by value, so, just start that kind of argument on the--java only pass value!
Read the introduction, and then combine the following examples to see if you understand?
Java code
package com.test;
class Value {
int i = 10;
}
public class Test {
public static void main(String[] args) {
Test t = new Test();
Value v = new Value ();
int i = 10;
System.out.println("a v.i = " + v.i + ", i = " + i);
t.test(v, i);
System.out.println("c v.i = " + v.i + ", i = " + i);
}
private void test(Value v, int i) {
v.i = 20;
i = 20;
System.out.println("b v.i = " + v.i + ", i = " + i);
}
}
The output results are:
A v.i = ten, I = 10
b V.I = +, I = 20
c V.I = +, I = 10