How to SWAP Two Numbers in Java using Temp Variable
In this blog, we will see How to SWAP Two Numbers in Java using Temp 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 using temp variable:
- Create two int variables and assign them with some values. Here we have taken a=20 and b=30 respectively.
- Now take another variable and name it as Temp
- Here, swap operation can be done by assigning the values of variables (a and b) using Temp as a Helper which is shown in the below code:
package Javaprograms; public class SwapTwoNumbersUsingTempVariable { public static void main(String[] args) { int a= 20; int b= 30; int temp; System.out.println("A vlaue before swapping is " +a); System.out.println("B vlaue before swapping is " +b); System.out.println("---------------------"); temp = a; a = b; a = temp; System.out.println("A vlaue after swapping is " +a); System.out.println("B vlaue 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.