Swap two numbers with and without a third variable

Description: Swap the values of a = 10 and b = 25. First use a third variable. Then do it without a third variable.

Hint:

  • With three variables: temp = a; a = b; b = temp;
  • Without: use addition and subtraction.

Solution

public class Main {
    public static void main(String[] args) {
        int a = 10, b = 25;

        int temp = a;           // way 1: a third variable
        a = b;
        b = temp;
        System.out.println("a = " + a + ", b = " + b);

        a = a + b;              // way 2: no third variable
        b = a - b;
        a = a - b;
        System.out.println("a = " + a + ", b = " + b);
    }
}
Output

a = 25, b = 10
a = 10, b = 25

How it works

  • The first way keeps one value safe in temp before it is replaced.
  • In the second way, a becomes the sum, and then each variable gets the other value by subtraction. (Be careful: with very big numbers the sum can overflow.)

Read Java Operators.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.