Blog
Articles to grow your career
Article
Often in the process of solving a particular problem, two variables must exchange values. There are two options for implementing value exchange:
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);
}
}
The 3rd variable is not introduced, the exchange is achieved by addition and subtraction:
Leave an application and get a free consultation from our manager.
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);
}
}