Consider the following method that is intended to swap the v

Consider the following method that is intended to swap the values or two integers: public static void falseSwap(int a, int b) {int temp = a; a = b; b = temp;} public static void main(String[] args) {int x = 3; int y = 4; falseSwap(x, y); System.out.println(x + \" \" + y);} Why doesn\'t the falseSwap method swap the contents of x and y?

Solution


public static void falseSwap(int a, int b){
  
   int temp = a;
   a = b;
   b = temp;
}

public static void main(String[] args){
  
   int x = 3;
   int y = 4;
   falseSwap(x, y);
   System.out.println(x+\" \"+y);
}

I java, we have PASS BY VALUE only,

so when we call: falseSwap(x, y) : It passes the values of x and
                       y to method falseSwap. So if you do anything
                       with these values in falseSwap metho, it will not affect the original value in main method
                      

 Consider the following method that is intended to swap the values or two integers: public static void falseSwap(int a, int b) {int temp = a; a = b; b = temp;}

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site