Here is a java program to swap two numbers, using third variable, without third variable, and swap two number input by user. All the java program here is follows object oriented approach.
Swap two numbers without third variable Java program
//Java program to swap two numbers
class SwapNum{
void swap(int num1, int num2){
System.out.println("Before swap num1 = "+num1);
System.out.println("Before swap num2 = "+num2);
num2 = num2 + num1;
num1 = num2 - num1;
num2 = num2 - num1;
System.out.println("After swap num1 = "+num1);
System.out.println("After swap num2 = "+num2);
}
}
class Main{
public static void main(String s[]){
SwapNum ob = new SwapNum();
ob.swap(2,1);
}
}
Output
Before swap num1 = 2
Before swap num2 = 1
After swap num1 = 1
After swap num2 = 2
Java program to swap two numbers using third variable
//Java program to swap two numbers
class SwapNum{
int num3;
void swap(int num1, int num2){
System.out.println("Before swap num1 = "+num1);
System.out.println("Before swap num2 = "+num2);
num3 = num1;
num1 = num2;
num2 = num3;
System.out.println("After swap num1 = "+num1);
System.out.println("After swap num2 = "+num2);
}
}
class Main{
public static void main(String s[]){
SwapNum ob = new SwapNum();
ob.swap(2,1);
}
}
Output
Before swap num1 = 2
Before swap num2 = 1
After swap num1 = 1
After swap num2 = 2
Java program to swap two numbers input by user
import java.util.Scanner;
//Java program to swap two numbers
class SwapNum{
int num3;
void swap(int num1, int num2){
System.out.println("Before swap num1 = "+num1);
System.out.println("Before swap num2 = "+num2);
num2 = num2 + num1;
num1 = num2 - num1;
num2 = num2 - num1;
System.out.println("After swap num1 = "+num1);
System.out.println("After swap num2 = "+num2);
}
}
class Main{
public static void main(String s[]){
Scanner sc = new Scanner(System.in);
SwapNum ob = new SwapNum();
System.out.println("Enter 1st number:");
int num1 = sc.nextInt();
System.out.println("Enter 2nd number:");
int num2 = sc.nextInt();
ob.swap(num1, num2);
}
}
Output
Enter 1st number:
2
Enter 2nd number:
1
Before swap num1 = 2
Before swap num2 = 1
After swap num1 = 1
After swap num2 = 2