Parameter passing mechanism of Java methods
•
Java
Parameter passing mechanism of Java methods
If formal parameters are declared in a Java method, you must specify parameter values for these formal parameters when calling the method. The actual value passed in is called an argument. This involves the parameter transfer mechanism and value transfer in Java.
Basic data type
Basic data type. Value transfer is the embodiment of value transfer.
public class TransferTempTest {
public static void main(String[] args) {
//基本数据类型参数传递
TransferTempTest test = new TransferTemptest();
int num1 = 10;
int num2 = 20;
System.out.println("进行交换前:");
System.out.println("num1 = " + num1 + ",num2 = " + num2);
test.swap(num1,num2);
System.out.println("交换之后:");
System.out.println("num1 = " + num1 + ",num2 = " + num2);
}
public void swap(int a,int b) {
int temp = a;
a = b;
b = temp;
System.out.println("交换过程中:");
System.out.println("num1 = " + a + ",num2 = " + b);
}
}
//运行结果
进行交换前:
num1 = 10,num2 = 20
交换过程中:
num1 = 20,num2 = 10
交换之后:
num1 = 10,num2 = 20
Memory diagram demonstration of the whole process:
As shown in the figure:
Reference data type
The basic data type, the embodiment of value transfer is the transfer of address value.
public class TransferTempTest {
public static void main(String[] args) {
//引用类型参数传递
DataTemp data = new DataTemp();
data.a = 2;
data.b = 4;
System.out.println("进行交换前:");
System.out.println("data.a = " + data.a + ",data.b = " + data.b);
data.swapClass(data);
System.out.println("进行交换后:");
System.out.println("data.a = " + data.a + ",data.b = " + data.b);
}
}
class DataTemp {
int a;
int b;
public void swapClass(DataTemp data) {
int temp = data.a;
data.a = data.b;
data.b = temp;
System.out.println("交换过程中:");
System.out.println("data.a = " + data.a + ",data.b = " + data.b);
}
}
//运行结果
进行交换前:
data.a = 2,data.b = 4
交换过程中:
data.a = 4,data.b = 2
进行交换后:
data.a = 4,data.b = 2
The memory diagram of the whole process shows:
As shown in the figure:
Comprehensive exercise
package com.my.pac05;
public class TransferTest {
public static void main(String[] args) {
TransferTest test = new Transfertest();
test.first();
}
public void first() {
int i = 5;
Value v = new Value();
v.i = 25;
second(v,i);
System.out.println(v.i);
}
public void second(Value v,int i) {
i = 0;
v.i = 20;
Value val = new Value();
v = val;
System.out.println(v.i + " " + i);
}
}
class Value {
int i = 15;
}
//运行结果
15 0
20
The memory diagram of the whole process shows:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码