Java Program to Swap Two Numbers Without Using Third Variable

Given two 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

public class SwapNumbers {
  public static void main(String[] args) {
    int x = 5;
    int y = 7;

    System.out.println("value of x - " + x);
    System.out.println("value of y - " + y);

    // Logic to swap
    x = x + y;
    y = x - y;
    x = x - y;

    System.out.println("Value of x after swap - " + x);
    System.out.println("Value of y after swap - " + y);


value of x - 5
value of y - 7
Value of x after swap - 7
Value of y after swap - 5

Related Posts

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

Share this post:

Leave a Reply

Your email address will not be published.

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