關於JAVA是值傳遞仍是引用傳遞的問題

1.概念spa

  值傳遞:方法調用時,實際傳入的是它的副本,在方法中對值的修改,不影響調用者的值。code

  引用傳遞:方法調用時,實際傳入的是參數的實際內存地址,調用者和調用方法所操做的參數都指向同一內存地址,因此方法中操做會影響調用者。對象

2.問題blog

  ① 值傳遞傳入的值,是它的副本是什麼意思?內存

  

public static void main(String[] args) {
        int a = 0;
     testValue(a); System.out.println(a); }
public void testValue(int a) { a = 8; }

  打印結果: 0hash

      此處調用方法後,a的值依然沒有變化。class

  

  ②當傳入的值是一個對象時,也不會發生變化麼?test

 

package com.test;

public class TestDemo {
    public static void main(String[] args) {
        TestDemo2 testDemo2 = new TestDemo2();
        System.out.println("調用前:" + testDemo2.hashCode());
        testValue(testDemo2);
        System.out.println("調用後:" + testDemo2.hashCode());
    }
    
    public static void testValue(TestDemo2 testDemo) {
        testDemo = new TestDemo2();
    }
}

class TestDemo2 {
    int age = 1;
}

 

  打印結果:引用

   調用前:366712642
   調用後:366712642方法

  這裏能夠看到testDemo2 的值依然沒有變化,調用先後所指向的內存地址值是同樣的。對傳入地址值的改變並不會影響原來的參數。

  ③既然是值傳遞,爲何參數是引用類型的時候,方法內對對象進行操做會影響原來對象,這真的是值傳遞麼?

 

package com.test;

public class TestDemo {
    public static void main(String[] args) {
        TestDemo2 testDemo2 = new TestDemo2();
        System.out.println("調用前:" + testDemo2.age);
        testValue(testDemo2);
        System.out.println("調用後:" + testDemo2.age);
    }
    
    public static void testValue(TestDemo2 testDemo) {
        testDemo.age = 9;
    }
}

class TestDemo2 {
    int age = 1;
}

 

打印結果

調用前:1
調用後:9

 對於這種狀況的解釋是,傳入的參數是testDemo2 對象地址值的一個拷貝,可是形參和實參的值都是同樣的,都指向同一個對象,因此對象內容的改變會影響到實參。

綜上所述:JAVA的參數傳遞確實是值傳遞,無論是基本參數類型仍是引用類型,形參值的改變都不會影響實參的值。若是是引用類型,形參值所對應的對象內部值的改變

會影響到實參。

 

 

若有疑問或寫的不恰當的地方歡迎在評論區指出!!

相關文章
相關標籤/搜索