Java program to swap two numbers
In this post, you will learn how to swap two numbers using the Java programming language. Such a type of question is generally asked in a programming interview.
Java program to swap two numbers using temporary variable
In the given example, we have taken a temporary variable for swapping two numbers. First, we have stored the value of a in the temporary variable temp. Then the value of b is stored in a. At last, the value of temp is stored in variable b.
import java.util.*;
public class Swap_Numbers {
public static void main(String[] args) {
int a, b, temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a and b: ");
a = sc.nextInt();
b = sc.nextInt();
System.out.println("Before swapping numbers: "+a +" "+ b);
// Value of first is assigned to temporary
temp = a;
// Value of second is assigned to first
a = b;
// Value of temporary is assigned to second
b = temp;
System.out.println("After swapping numbers: "+a +" " + b);
System.out.println( );
}
}
Output of the above code:
Enter the value of a and b: 23 53
Before swapping numbers: 23 53
After swapping numbers: 53 23
Java program to swap two numbers without using temporary variable
In the given example, we have applied simple mathematics to swap two numbers instead of using temporary variable. First, subtract the second variable from the first variable and assign that value to the first variable. Next, add the value of both the variables and assign it to the second variable. Again, subtract the value of the first variable from the second variable and assign that value to the first variable.
import java.util.*;
public class Swap_Numbers {
public static void main(String[] args) {
int x, y;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of x and y: ");
x = sc.nextInt();
y = sc.nextInt();
System.out.println("Before swapping numbers: "+x +" "+ y);
x = x - y;
y = x + y;
x = y - x;
System.out.println("After swapping numbers: "+x +" "+ y);
}
}
Output of the above code:
Enter the value of x and y: 57 41
Before swapping numbers: 57 41
After swapping numbers: 41 57
Related Articles
Sort array in ascending order JavaAutomorphic number in Java
Pascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java