Swap Variables without Third Variable in Java Programming
Here we have written a Program To Swap Variables without 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.
Also Read: Swap Two Integer Variables using Bitwise Operators in Java
Program To Swap Variables without 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 24 | 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); num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; 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 without using Temporary (Third) Variable in Java Programming Language. You can also Swap Two Variables without using a Third (Temporary) Variable.
Also Read: Java Program To Swap Two Variables using Temporary Variable
In case you get any Compilation Errors with this Java Program To Swap Two Numbers without using Third (Temporary) Variable or you have any doubt about it, mention it in the Comment Section.