Friday, November 16, 2018

Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program

Write a Java program to swap or exchange two numbers without using any temporary variable is a frequently asked Java interview question.

This post shows one way to solve this. Logic here is to get the sum of both the numbers in one of the variable, numbers can be swapped then by subtracting from that sum.

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 Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


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. Java Program to Reverse a Number

You may also like-

  1. Count Number of Words in a String - Java Program
  2. How to Reverse a String in Java
  3. Matrix Multiplication Java Program
  4. Marker interface in Java
  5. Object creation using new operator in Java
  6. Conditional Operators in Java
  7. Array in Java
  8. String in Java