In  this tutorial, we will see “How to Swap two numbers without using a third variable in Java?”

swapping of two numbers without using third variable in java

Java – Swap two numbers without using a third variable? Share on X

/**
 * Using Java, Swap two numbers without using a third variable
 * @author Deepak Verma
 *
 */

public class Swap_Two_Number_Without_Using_Third_Variable_Java {

	public static void main(String[] args) {

        int number1 = 10;
        int number2 = 20;
        
        System.out.println("Before swapping:\n number1 = " + number1 + " and number2 = " + number2);
       
        number1 = number1 + number2;
        number2 = number1 - number2;
        number1 = number1 - number2;
        
        System.out.println("After swapping:\n number1 = " + number1 + " and number2 = " + number2);

	}

}

 

Output:

Before swapping:
 number1 = 10 and number2 = 20
After swapping:
 number1 = 20 and number2 = 10

swap two numbers without using third variable in java

Java – Swap two numbers without using a third variable? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts