0

I a, getting the output as 10 9 9 10 for this program but I am not able to understand why swapping is not working.

Given below is the code:

public class Swap {

public static void main(String[] args) {
    int a=9;
    int b=10;

    swap(a, b);

    System.out.println(a);
    System.out.println(b);
}

public static void swap(int a ,int b){

    int temp=0;
    temp=a;
    a=b;
    b=temp;
    System.out.println(a);
    System.out.println(b);


}
Rajeev Akotkar
  • 1,377
  • 4
  • 26
  • 46
  • This is because you are swapping the local variables a and b of the method, not those of the main method. Since you never change the values of them, they'll remain the same. – Stultuske Apr 30 '15 at 06:57
  • read about `call by reference` and `call by value` – Jens Apr 30 '15 at 06:58
  • possible duplicate of http://stackoverflow.com/questions/3624525/how-to-write-a-basic-swap-function-in-java – Kaustubh Khare Apr 30 '15 at 07:01

0 Answers0