Swap Integers Without Temporary Variable in Java

It’s quite amusing to see how different variations of solutions for the same questions are thereby different individuals. From pretty ancient times maths has played a very vital role in civilizations. Not to mention how everything around us revolves mathematically. Now programming is more or less similar to that. It’s the second version of maths where to solve real-world problems you need to apply real-world mathematical concepts. However, as we’re talking about maths, how about writing a program to swap Integers. So today let’s write a simple program to Swap Integers Without Temporary Variable in Java

What’s The Approach?

  • Let us consider x & y to be the numbers we want to swap with each other. Now the catch is to do this without using a temporary variable.
  • Firstly we’ll store the addition of two variables in, one of the variables. That is, x = x + y.
  • Now, we will subtract the value of y from x and assign this new value to y. i.e, y = x - y this way we’ll store the value of variable x into variable y.
  • Next, we’ll again subtract the value of y from x and assign this new value to x. i.e, x = x - y by doing this we’ll store the value of variable y into x.
  • After the above two instructions finish executing we’ll print the values of x & y.

Also Read: Print Sum of Digits in Given Number using Java

Java Program To Swap Integers Without Temporary Variable

 

Input:

x = 10, y = 5

Output:

x = 5, y = 10

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *