iT邦幫忙

2022 iThome 鐵人賽

DAY 28
0

Call by value:將實際參數傳遞給方法,方法內的參數與傳入參數值的記憶體位置不同,如int x 與 number

Call by reference:將實際參數傳遞給方法引用,故方法內改變參數連帶時參一起改變,如int[] y 與 numbers[0]

public class Try {
    public static void main(String[] args) {
        int x= 1;
        int[] y=new int[10];

        m(x,y);

        System.out.println("x is "+x);
        System.out.println("y[0] is "+y[0]);
    }

    public static void m(int number, int[] numbers){
        number=1001;
        numbers[0]=5555;
    }
}
// x is 1
// y[0] is 5555

再來一個案例

public class Try {
    public static void main(String[] args) {
        int[] a = {1, 2};

        // Swap elements using the swap method
        System.out.println("Before invoking swap");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");
        swap(a[0], a[1]);
        System.out.println("After invoking swap");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");

        // Swap elements using the swapFirstTwoInArray method
        System.out.println("Before invoking swapFirstTwoInArray");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");
        swapFirstTwoInArray(a);
        System.out.println("After invoking swapFirstTwoInArray");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");
    }

    /**
     * Swap two variables
     */
    public static void swap(int n1, int n2) {
        int temp = n1;
        n1 = n2;
        n2 = temp;
    }

    /**
     * Swap the first two elements in the array
     */
    public static void swapFirstTwoInArray(int[] array) {
        int temp = array[0];
        array[0] = array[1];
        array[1] = temp;
    }
}
// Before invoking swap
// array is {1, 2}
// After invoking swap
// array is {1, 2}
// Before invoking swapFirstTwoInArray
// array is {1, 2}
// After invoking swapFirstTwoInArray
// array is {2, 1}

上一篇
遞迴|河內塔
下一篇
Codewars|Bit Counting
系列文
寫寫歷年職場經歷過的大小事或近期所學習的知識啟發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言