Java Program to Swap Two Numbers Without Using Third Variable

Given two int variables write a Java program to swap the values of the variables without using third variable is one question asked in many interviews. In this post we’ll see one way of doing that.

Logic used here is to add both the variables and hold that value in one of the variable. Then subtracting another variable from the sum and assigning the subtracted value to the same variable will swap the values.

Java code to swap the values of two variables

Output

That’s all for the topic Java Program to Swap Two Numbers Without Using Third Variable. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.