關(guān)于變量的賦值:
如果變量是基本數(shù)據(jù)類型,此時(shí)賦值的是變量所保存的數(shù)據(jù)值。
如果變量是引用數(shù)據(jù)類型,此時(shí)賦值的是變量所保存的數(shù)據(jù)的地址值。
public class ValueTransferTest {
public static void main(String[] args) {
System.out.println("***********基本數(shù)據(jù)類型:****************");
int m = 10;
int n = m;
System.out.println("m = " + m + ", n = " + n);
n = 20;
System.out.println("m = " + m + ", n = " + n);
System.out.println("***********引用數(shù)據(jù)類型:****************");
Order o1 = new Order();
o1.orderId = 1001;
Order o2 = o1;//賦值以后,o1和o2的地址值相同,都指向了堆空間中同一個(gè)對(duì)象實(shí)體。
System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " +o2.orderId);
o2.orderId = 1002;
System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " +o2.orderId);
}
}
class Order{
int orderId;
}
方法的形參的傳遞機(jī)制:值傳遞
1.形參:方法定義時(shí),聲明的小括號(hào)內(nèi)的參數(shù)
實(shí)參:方法調(diào)用時(shí),實(shí)際傳遞給形參的數(shù)據(jù)
2.值傳遞機(jī)制:
如果參數(shù)是基本數(shù)據(jù)類型,此時(shí)實(shí)參賦給形參的是實(shí)參真實(shí)存儲(chǔ)的數(shù)據(jù)值。
如果參數(shù)是引用數(shù)據(jù)類型,此時(shí)實(shí)參賦給形參的是實(shí)參存儲(chǔ)數(shù)據(jù)的地址值。
public class ValueTransferTest1 {
public static void main(String[] args) {
int m = 10;
int n = 20;
System.out.println("m = " + m + ", n = " + n);
//交換兩個(gè)變量的值的操作
// 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 ValueTransferTest2 {
public static void main(String[] args) {
Data data = new Data();
data.m = 10;
data.n = 20;
System.out.println("m = " + data.m + ", n = " + data.n);
//交換m和n的值
// int temp = data.m;
// data.m = data.n;
// data.n = temp;
ValueTransferTest2 test = new ValueTransferTest2();
test.swap(data);
System.out.println("m = " + data.m + ", n = " + data.n);
}
public void swap(Data data){
int temp = data.m;
data.m = data.n;
data.n = temp;
}
}
class Data{
int m;
int n;
}
看到這里,本篇關(guān)于Java基礎(chǔ)知識(shí)的形參和實(shí)參的內(nèi)容就介紹到此結(jié)束了,如果你還要了解學(xué)習(xí)更多關(guān)于Java基礎(chǔ)知識(shí)的內(nèi)容,你可以多多關(guān)注W3Cschool相關(guān)內(nèi)容的文章。如果覺得本篇文章還不錯(cuò),還希望大家能夠多多支持!