How to SWAP Two Numbers in Java Without Temp variable or Without Third variable
In this blog, we will see How to SWAP Two Numbers in Java without Temp Variable or without third variable. This will be asked in the most of the interview questions.
In the below snippet, we have done the following to swap two numbers without using temp variable:
- Create two int variables and assign them with some values. Here we have taken a=20 and b=30 respectively.
- Here, swap operation can be done by assigning the values of variables (a and b) to one another as below and getting the latest values in those respective variables which is shown in the below code:
package Javaprograms; public class SwapTwoNumbersWithoutTempVariable { public static void main(String[] args) { int a = 20; int b = 30; System.out.println("a value before swapping is:" +a); System.out.println("b value before swapping is:" +b); System.out.println("---------------------------------"); a = a+b; // a=20 + b=30; now a value = 50 b = a-b; // a=50 - b=30; now b value = 20 a = a-b; // a=50 - b=20; now a value = 30 System.out.println("a value after swapping is:" +a); System.out.println("b value after swapping is:" +b); } }
Output: -------- a value before swapping is:20 b value before swapping is:30 --------------------------------- a value after swapping is:30 b value after swapping is:20
Please watch the Youtube video for better understanding.