June 22, 2022

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);
  }
}
Output
value of x - 5
value of y - 7
Value of x after swap - 7
Value of y after swap - 5

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

No comments:

Post a Comment