Swap Two Numbers in Java
Here you will get the program code of Swap two numbers in java with the help of third variable. Swapping with a third variable is a process of exchanging the values of two variables using with third temporary variable.
For example:-
int x = 5;
int y = 10;
int temp = x;
x = y;
y = temp;
Program to Swap two numbers in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //Swap Two Numbers in Java import java.util.Scanner; class SwapTwoNumbers { 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); temp=a; a=b; b=temp; System.out.println("\nAfter Swap: " + " a= " + a + "\tb= "+b); } } |
Output
Check out our other Java Programming Examples