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}