
第5頁,共 12 頁
【2】7.編譯並執行下列的程式時,輸出結果為何?
public static void main(String[] args) {
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " +
num1 + " and num2 is " + num2);
// Invoke the swap method to attempt to swap two variables
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " +
num1 + " and num2 is " + num2);
}
/** Swap two variables */
public static void swap(int n1, int n2) {
System.out.println("tInside the swap method");
System.out.println("ttBefore swapping n1 is " + n1 + " n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("ttAfter swapping n1 is " + n1 + " n2 is " + n2);
}
Before invoking the swap method, num1 is 1 and num2 is 2
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After invoking the swap method, num1 is 1 and num2 is 2
Before invoking the swap method, num1 is 1 and num2 is 2
Inside the swap method
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After invoking the swap method, num1 is 1 and num2 is 2
Before invoking the swap method, num1 is 1 and num2 is 2
Before swapping n1 is 1 n2 is 2
After swapping n1 is 1 n2 is 2
Inside the swap method
After invoking the swap method, num1 is 1 and num2 is 2
Before invoking the swap method, num1 is 1 and num2 is 2
Before swapping n1 is 1 n2 is 2
After invoking the swap method, num1 is 1 and num2 is 2