Best Way In Java To Swap Two Numbers

Sharing is healthy !!

Hello everyone!! Today we will discuss best way in java to swap two numbers.

Well, there are two ways to swap numbers in java,

  1. with temporary variable
  2.  without temporary variable

example: Best Way In Java To Swap Two Numbers

Also Read – Add Two Numbers With Bitwise Operator

/* WITH TEMPORARY VARIABLE */

import java.util.Scanner;

public class Swap_Two_Numbers {

public static void main(String[] args) {
 
int a;
int b;
int swap;
 
System.out.println("Please enter two integers to swap: ");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
 
System.out.println("Before swap: a = " + a + "\nBefore swap: b = " + b);
swap = a;
a = b;
b = swap;
System.out.println("After swap: a = " + a + "\nAfter swap: b = " + b);

}

}

Output:

Best Way In Java To Swap Two Numbers


/* WITHOUT TEMPORARY VARIABLE */

import java.util.Scanner;

public class Swap_Two_Numbers {

public static void main(String[] args) {
 
int a;
int b; 
 
System.out.println("Please enter two integers to swap: ");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
 
System.out.println("Before swap: a = " + a + "\nBefore swap: b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swap: a = " + a + "\nAfter swap: b = " + b);

}

}

Output:

Please enter two integers to swap: 10 5
Before swap: a = 10
Before swap: b = 5
After swap: a = 5
After swap: b = 10

Sharing is healthy !!

Leave a Reply

Your email address will not be published.