Swap Numbers Without Using Third Variable

  1. /*

  2. Swap Numbers Without Using Third Variable Java Example

  3. This Swap Numbers Java Example shows how to

  4. swap value of two numbers without using third variable using java.

  5. */

  6.  

  7. public class SwapElementsWithoutThirdVariableExample {

  8.  

  9. public static void main(String[] args) {

  10.  

  11. int num1 = 10;

  12. int num2 = 20;

  13.  

  14. System.out.println("Before Swapping");

  15. System.out.println("Value of num1 is :" + num1);

  16. System.out.println("Value of num2 is :" +num2);

  17.  

  18. //add both the numbers and assign it to first

  19. num1 = num1 + num2;

  20. num2 = num1 - num2;

  21. num1 = num1 - num2;

  22.  

  23. System.out.println("Before Swapping");

  24. System.out.println("Value of num1 is :" + num1);

  25. System.out.println("Value of num2 is :" +num2);

  26. }

  27.  

  28.  

  29. }

  30.  

  31. /*

  32. Output of Swap Numbers Without Using Third Variable example would be

  33. Before Swapping

  34. Value of num1 is :10

  35. Value of num2 is :20

  36. Before Swapping

  37. Value of num1 is :20

  38. Value of num2 is :10

  39. */

0 comments: