Swap Two Numbers without Third Variable in Java
Here you will learn to Swap Two Numbers without Third Variable in Java, Which usually involves using mathematical operations to switch the values of two variables. For example, one could use the following equation to switch the values of two variables, x and y:
x = x + y;
y = x – y;
x = x – y;
Program to Swap Two Numbers without Third Variable in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.Scanner; class SwapTwoNumbers2 { public static void main(String args[]) { int a,b,temp; System.out.println("\nEnter the value of a and b "); Scanner in = new Scanner(System.in); a = in.nextInt(); b = in.nextInt(); System.out.println("\nBefore Swap: " + " a= " + a + "\tb= "+b); // swapping a = a + b; b = a - b; a = a - b; System.out.println("\nAfter Swap: " + " a= " + a + "\tb= "+b); } } |
Output
C:\CodeRevise\java>javac SwapTwoNumbers2.java
C:\CodeRevise\java>java SwapTwoNumbers2
Enter the value of a and b 4 8
Before Swap: a= 4 b= 8
After Swap: a= 8 b= 4
Check out our other Java Programming Examples