Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 895

How to swap or exchange two numbers without using any temporary variable - Java Program

$
0
0

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

  1. Print odd-even numbers using threads and wait-notify
  2. Factorial program in Java
  3. Fibonacci series program in Java
  4. Displaying prime numbers - Java program
  5. How to reverse number - Java Program

You may also like -

>>>Go to Java Programs page


Viewing all articles
Browse latest Browse all 895

Trending Articles