Blog

Articles to grow your career

Article

Method swap in Java – Algorithms for interview

Often in the process of solving a particular problem, two variables must exchange values. There are two options for implementing value exchange:

Option 1: Swap Values ​​Using a Temporary Variable

We introduce a temporary variable that will temporarily hold the value from one variable:

int tmp = a;
a = b;
b = tmp;

For example:

public class ChangeValues1 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

        int tmp = a;
        a = b;
        b = tmp;

        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Option 2: Swap Values ​​without a Temporary Variable

The 3rd variable is not introduced, the exchange is achieved by addition and subtraction:

Do you want to join us?

Leave an application and get a free consultation from our manager.

  • Help in choosing a direction
  • Course consultation
  • Additional materials for the start
a = a + b;
b = a - b;
a = a - b

For example:

public class ChangeValues2 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

        a = a + b; // a = 8, b = 5
        b = a - b; // a = 8, b = 3
        a = a - b; // a = 5, b = 3

        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}
Alex Kara
By Alex Kara on Apr 01, 2022
Coding tasks for interviews