Swap Two Numbers without Temp Variable in Java


Q. Write a Java program to swap two numbers without using a temp variable

import java.util.Scanner;

public class SwapWithoutTemp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input two numbers
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        // Display original values
        System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);

        // Swap without using a temporary variable
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        // Display swapped values
        System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);

        scanner.close();
    }
} 

Q. Write an algorithm to swap two numbers without using a temp variable

1. Start
2. Read two numbers: num1 and num2
3. Perform num1 = num1 + num2
4. Perform num2 = num1 - num2
5. Perform num1 = num1 - num2
6. Print the swapped values
7. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.