2015-09-07 57 views
0

這些對我來說看起來是一樣的,但爲什麼他們產生不同的輸出?我是Java的新手,所以請耐心等待!在Java中簡單交換

該交換功能的工作原理

//Swap 1 Output is "4,8" 
public class SampleSwap { 
public static void main(String[] args) 
{ 
    int a=8; 
    int b=4; 
    int temp; 

    temp=a; 
    a=b; 
    b=temp; 

    System.out.println("a:" +a); 
    System.out.println("b:" +b); 
} 
} 

該交換功能不起作用

//Swap 2 Output is "8,4" 
public class Swap { 
public static void main(String[] args) { 
    int a = 8, b = 4; 
    swap(a, b); 
     System.out.print(a + "," + b); 
    System.out.println(); 
} 

public static void swap(int a, int b) { 
    int tmp = a; 
    a = b; 
    b = tmp; 
} 
} 

回答