04_javaSE面試題:方法的參數傳遞機制

題目

import java.util.Arrays;

/**
 * @author kevin
 * @date 2019/7/10 9:46
 */
public class Exam4 {
    public static void main(String[] args) {
        int i= 1;
        String str = "hello";
        int[] arr = {1,2,3,4,5};
        MyData my = new MyData();
        change(i,str,arr,my);
        System.out.println("i=" +i );
        System.out.println("str=" + str);
        System.out.println("arr="+ Arrays.toString(arr));
        System.out.println("my.a="+my.a);
    }
    public static void change(int i,String str,int[] arr,MyData my){
        i +=1;
        str += "world";
        arr[0] += 1;
        my.a +=1;
    }
}
class MyData{
    int a = 10;
}

運行結果

i=1
str=hello
num=2
arr=[2, 2, 3, 4, 5]
my.a=11

分析

首先,不要糾結於Pass By Value 和 Pass By Reference 的字面上的意義,否則很容易陷入所謂的“一切傳引用其實本質上是傳值”這種並不能解決問題無意義論戰中。

  • 對象類型永遠傳引用;
  • 基本類型傳值。

下面畫了一張圖更利於解釋

玩的開心!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章