Objective
When reading the Java programming idea recently, the author's interpretation of the "reference (handle)" in Java is not very clear, so we will discuss in an experimental way everything in Java is "passed by value", thus deepening understanding.
Body Scenario One: When a parameter is a base data type (for example: int)
public class TestReference { public static void testOne(int i){ i = 2; System.out.println("test函数中的变量值:" + i); } public static void main(String[] args) { // TODO Auto-generated method stub int a = 1; TestReference.testOne(a); System.out.println("main函数中的变量值:" + a); }}
Operation Result:
The value of the variable in the test function: 2
The value of the variable in the main function: 1
This shows: when a parameter is a base data type, the pass of the parameter is passed as a copy of the value
Scenario two: The "pass by reference" effect occurs when the argument is an object
package test;public class TestReference { public static void testTwo(B c){ c.data = 2; System.out.println("test函数中的变量值:" + c.data); } public static void main(String[] args) { // TODO Auto-generated method stub B b = new B(); b.data = 1; TestReference.testTwo(b); System.out.println("main函数中的变量值:" + b.data); }}
Operation Result:
The value of the variable in the test function: 2
The value of the variable in the main function: 2
This shows that the parameters of the function in this example do operate the argument variable in the same way as the copy address .
Scenario Three: Creating a new object for a parameter in a function
public class TestReference { public static void testThree(String str){ str = new String("new"); System.out.println("test函数中的变量值:" + str); } public static void main(String[] args) { // TODO Auto-generated method stub String str = new String("old"); TestReference.testThree(str); System.out.println("main函数中的变量值:" + str); }}
Operation Result:
Variable value in the test function: New
The value of the variable in the main function: old
This shows: Real parametric the object address in the way of copy address to the parameter variable, but in the function of the process, the shape parametric is given the address of the new object, so after the operation of the parameter variables and real parametric will not have any relationship.
Summarize
The so-called "everything is transmitted value" for the basic data type, refers to the variable is worth copying, and for the object (or string, Integer and other wrapper basic type), refers to the object address of the copy, that is, the value passed is the address of the object.
About the concept of "references" in Java