Learnitweb

Java Program to swap two numbers without using a third variable(method 1).

This approach uses addition and subtraction to swap two numbers. The logic to solve this problem is to first assign one of the two numbers with the sum of two numbers. Since, this number will now have the sum of two numbers, assign second number the difference of first number(which is now the sum of two numbers) and the second number. Now assign first number the difference of first number(which is the now the sum of two numbers) and the second number (which will now have the value of first number).

import java.util.Scanner;
public class SwapNumbersWithoutThirdVariable {
  public static void main(String args[]) {
    int firstNumber;
    int secondNumber;
    int temp;
    
    System.out.println("Enter first number:");
    Scanner in = new Scanner(System.in);
    
    firstNumber = in.nextInt();
    
    System.out.println("Enter second number:");
    secondNumber = in.nextInt();
    
    System.out.println("Before Swapping\nx = "+firstNumber+"\ny = "+secondNumber);
    
    firstNumber = firstNumber + secondNumber;
    secondNumber = firstNumber - secondNumber;
    firstNumber = firstNumber - secondNumber;
    
    System.out.println("After Swapping\nx = "+firstNumber+"\ny = "+secondNumber);
  }
}

Output

Enter first number:
10
Enter second number:
6
Before Swapping
x = 10
y = 6
After Swapping
x = 6
y = 10