How to swap or exchange two numbers without using any temporary variable is asked quite frequently in Java interview questions.
This post shows one way to solve this -
public class Swap {
public static void main(String[] args) {
int a = 7;
int b = 8;
System.out.println("value of a - " + a);
System.out.println("value of b - " + b);
// Swapping logic
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swap value of a - " + a);
System.out.println("After swap value of b - " + b);
}
}
Output
value of a - 7
value of b - 8
After swap value of a - 8
After swap value of b - 7
That's all for this topic How to swap or exchange two numbers without using any temporary variable. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -