Swap Numbers Without Using Third Variable Java Example

  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. */

Visit Java Example Forums to request Java examples or ask Java questions!
OR
Try out our new Java Search Engine




Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!