Saturday, 7 January 2017

Swap Numbers Without Using Third Variable Java Example

  1. public class SwapElementsWithoutThirdVariableExample {
  2.  
  3.         public static void main(String[] args) {
  4.                
  5.                 int num1 = 10;
  6.                 int num2 = 20;
  7.                
  8.                 System.out.println("Before Swapping");
  9.                 System.out.println("Value of num1 is :" + num1);
  10.                 System.out.println("Value of num2 is :" +num2);
  11.                
  12.                 //add both the numbers and assign it to first
  13.                 num1 = num1 + num2;
  14.                 num2 = num1 - num2;
  15.                 num1 = num1 - num2;
  16.                
  17.                 System.out.println("Before Swapping");
  18.                 System.out.println("Value of num1 is :" + num1);
  19.                 System.out.println("Value of num2 is :" +num2);
  20.         }
  21.  
  22.  
  23. }

No comments: