Tuesday, November 2, 2021

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 Java Program
  2. Factorial Program in Java
  3. Fibonacci Series Program in Java
  4. Java Program to Display Prime Numbers
  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 With Examples
  7. Array in Java With Examples
  8. String in Java Tutorial

No comments:

Post a Comment