Friday, 12 May 2017

How to swap two variables in one line code in Java?

Rules:
           a = 10;  b = 20;
a = a ^ b;
b = a ^ b;
a = a ^ b;

public classSwapNumber {

      /**
       * Print swapped value
       * @param a
       * @param b
       */
      private static void printSwappedNumbers(int a, int b) {
            System.out.println("Value of a# "+a+" value of b# "+b);
            a = a ^ b ^ (b=a);
            System.out.println("Value of a# "+a+" value of b# "+b);
      }
     
      /**
       * Driver Method
       * @param args
       */
      public static void main(String[] args) {
            int a = 10, b = 20;
            printSwappedNumbers(a,b);
      }
}


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...