Java - Swap Two Numbers
In this post, you will learn how to code Java Program to Swap Two Numbers using 2 different methods.
1. Using third variable
2. Without using third variable
Java Program to Swap Two Numbers
Method 1 : using third variable
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String []args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter first number: ");
int firstNumber = Integer.parseInt(br.readLine());
System.out.println("Enter second number: ");
int secondNumber = Integer.parseInt(br.readLine());
//Before Swapping two numbers
System.out.println("Before Swapping :");
System.out.println("First number is "+firstNumber);
System.out.println("Second number is "+secondNumber);
//Swapping the numbers
int temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp;
//After Swapping two numbers
System.out.println("After Swapping :");
System.out.println("First number is "+firstNumber);
System.out.println("Second number is "+secondNumber);
}
}
Output:
Enter first number:
122
Enter second number:
222
Before Swapping :
First number is 122
Second number is 222
After Swapping :
First number is 222
Second number is 122
Method 2 : Without using third variable
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String []args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter first number: ");
int firstNumber = Integer.parseInt(br.readLine());
System.out.println("Enter second number: ");
int secondNumber = Integer.parseInt(br.readLine());
//Before Swapping two numbers
System.out.println("Before Swapping :");
System.out.println("First number is "+firstNumber);
System.out.println("Second number is "+secondNumber);
//Swapping the numbers without using third variable
firstNumber = firstNumber + secondNumber;
secondNumber = firstNumber - secondNumber;
firstNumber = firstNumber - secondNumber;
//After Swapping two numbers
System.out.println("After Swapping :");
System.out.println("First number is "+firstNumber);
System.out.println("Second number is "+secondNumber);
}
}
Output:
Enter first number:
127
Enter second number:
323
Before Swapping :
First number is 127
Second number is 323
After Swapping :
First number is 323
Second number is 127