一、概念
方法的形参的传递机制:值传递
1.形参:方法定义时,声明小括号内的参数
实参:方法调用时,实际传递给形参的数据
2.值传递机制
如果参数是基本数据类型,此时实参赋给形参的是实参真实存储的数据值。
二、参考代码
public class ValueTransferTest1 {
public static void main(String[] args) {
int m = 10;
int n = 20;
System.out.println("m = " + m + ", n = " + n);
//交换两个变量的值的操作
// int temp = m ;
// m = n;
// n = temp;
ValueTransferTest1 test = new ValueTransferTest1();
test.swap(m, n);
System.out.println("m = " + m + ", n = " + n);
}
public void swap(int m,int n){
int temp = m ;
m = n;
n = temp;
}
}
public class ValueTransferTest1 {
public static void main(String[] args) {
int m = 10;
int n = 20;
System.out.println("m = " + m + ", n = " + n);
//交换两个变量的值的操作
// int temp = m ;
// m = n;
// n = temp;
ValueTransferTest1 test = new ValueTransferTest1();
test.swap(m, n);
System.out.println("m = " +m + ", n = " + n);
}
public void swap(int x,int y){
int temp = x ;
x= y;
y = temp;
//System.out.println("m = " +x + ", n = " + y);
}
}
结果不能交换两个的值
package project01;
public class ValueTransferTest1 {
public static void main(String[] args) {
int m = 10;
int n = 20;
System.out.println("m = " + m + ", n = " + n);
//交换两个变量的值的操作
// int temp = m ;
// m = n;
// n = temp;
ValueTransferTest1 test = new ValueTransferTest1();
test.swap(m, n);
//System.out.println("m = " +m + ", n = " + n);
}
public void swap(int x,int y){
int temp = x ;
x= y;
y = temp;
System.out.println("m = " +x + ", n = " + y);
}
}
结果:如此可以交换两个的值