更新時(shí)間:2022-08-17 08:08:36 來源:動力節(jié)點(diǎn) 瀏覽2229次
有些小伙伴對Java傳參方式還不是很了解,那么就由動力節(jié)點(diǎn)小編來告訴大家。
程序設(shè)計(jì)語言將實(shí)參傳遞給方法(或函數(shù))的方式分為兩種:Java傳值和引用傳值
方法接收的是實(shí)參值的拷貝,會創(chuàng)建副本。

方法接收的直接是實(shí)參所引用的對象在堆中的地址,不會創(chuàng)建副本,對形參的修改將影響到實(shí)參。

基本數(shù)據(jù)類型
public static void main(String[] args) {
int a = 129;
int b = 130;
intSwap(a, b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void intSwap(int value1, int value2) {
int temp = value1;
value1 = value2;
value2 = temp;
}
// 運(yùn)行結(jié)果:a = 129;b = 130;
基本數(shù)據(jù)類型的引用類型
public static void main(String[] args) {
int a = 129;
int b = 130;
intSwap(a, b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void integerSwap(Integer value1, Integer value2) {
Integer temp = value1;
value1 = value2;
value2 = temp;
}
// 運(yùn)行結(jié)果:a = 129;b = 130;
對象類型(與數(shù)組類型類似)
public static void main(String[] args) {
TestClass a = new TestClass("a", 129);
TestClass b = new TestClass("b", 130);
objSwap(a, b);
System.out.println(a);
System.out.println(b);
}
private static void objSwap(TestClass value1, TestClass value2) {
TestClass temp = value1;
value1 = value2;
value2 = temp;
System.out.println(value1);
System.out.println(value2);
value2.value = 0;
}
static class TestClass {
public String key;
public Integer value;
public TestClass(String key, Integer value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return key + " = " + value;
}
}
// 運(yùn)行結(jié)果:a = 0;b = 130;
以上就是關(guān)于“Java傳參方式的詳細(xì)介紹”的介紹,大家如果對此比較感興趣,可以關(guān)注一下動力節(jié)點(diǎn)的Java教程,里面有更豐富的知識等著大家去學(xué)習(xí),希望對大家能夠有所幫助哦。
相關(guān)閱讀

初級 202925

初級 203221

初級 202629

初級 203743