0

How do I get this working because the swap is not working as intended? I believe that my scope of my local variables is incorrect and I am having trouble where to place them. My code outputs 4, 5 but it's supposed to output 5, 4. I also can't add a print statement in the swap method.

   public class SwapTest {      
      public static void main(String[] args) {        
        int num1 = 4;        
        int num2 = 5;        
        swap(num1, num2);        
        System.out.println(num1 + " " + num2);   
   }   
   //a method that swaps the values of two int variables.   
   public static void swap(int num1, int num2){       
       int num3;       
       num3 = num1;    
       num1 = num2;       
       num2 = num3;    
   } 
} 
m.dao
  • 1
  • 2
  • 1
    This basically can't work without some serious finagling. – markspace Apr 07 '16 at 22:31
  • 2
    See [Is Java “pass-by-reference” or “pass-by-value”?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value/40523#40523) – Andreas Apr 07 '16 at 22:39
  • @markspace I'm intrigued as to what "finagling" could get this to work. (Unless you mean "doing it in a completely different way" :o) – Andy Turner Apr 07 '16 at 22:48
  • Perhaps this would be a better duplicate: [Is it possible to swap two variables in Java?](http://stackoverflow.com/questions/10393690/is-it-possible-to-swap-two-variables-in-java) – Andy Turner Apr 07 '16 at 22:49
  • Basically you could return the two values in a temporary object (say an array) or make the local variables in `main` instance variables instead. That's what I mean by 'finagling,' but it probably qualifies as being completely different too. – markspace Apr 07 '16 at 23:23

0 Answers0