Swap Variables using Third Variable in Java Programming
Here we have written a Program To Swap Variables using Third Variable in Java Programming Language. Third Variable is also sometimes known as a Temporary Variable. Two Numbers can be Replaced or Swapped with each other by using a Temporary Variable which is also known as Third Variable.
Also Read: Java Code To Swap Two Integer Variables using Bitwise Operators
Code To Swap Variables using Third Variable in Java Language
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.io.*; import java.util.*; class SwapVariables { public static void main(String args[]) { int num1, num2, temp; Scanner sc = new Scanner(System.in); System.out.println("nEnter First Integer: "); num1 = sc.nextInt(); System.out.println("nEnter Second Integer: "); num2 = sc.nextInt(); System.out.println("nBefore Swapping:"); System.out.println("nFirst Number = " + num1 + "nSecond Number = " + num2); temp = num1; num1 = num2; num2 = temp; System.out.println("nAfter Swapping:"); System.out.println("nFirst Number = " + num1 + "nSecond Number = " + num2); System.out.println("n"); } } |
Output

It is a Simple Technique to Swap Variables using Third (Temporary) Variable in Java Programming Language. You can also Swap Two Variables without using a Temporary (Third) Variable.
Also Read: Swap Two Variables without using Temporary Variable in Java
In case you get any Compilation Errors with this Java Program To Swap Two Numbers using Third (Temporary) Variable or you have any doubt about it, mention it in the Comment Section.