Java Program to Swap two Numbers without using third variable

(2730 Views) Problem Statement

Write a Java Program to Swap two numbers without using a Third Variable

OR

Write a Java program to Swap two numbers without using temporary variable
For eg.
Input: a=24 b=36
Output: a=36 b=24

Method 1 (Swapping Using Arithmetic Operators)

FlowChart Or Pseudocode to Swap two Number without using Third or Temp variable Using Arithmetic Operators swapWithoutVariable.java
import java.util.Scanner; public class swapWithoutVariable{ public static void main(String[] args){ int a,b; Scanner sc=new Scanner(System.in); a=sc.nextInt(); b=sc.nextInt(); a=a+b; b=a-b; a=a-b; System.out.println("a= "+a); System.out.println("b= "+b); } }

Method 2 (Swapping Using Bitwise XOR)

FlowChart Or Pseudocode to Swap two Number without using Third or Temp variable Using Bitwise XOR swapWithoutVariable2.java
import java.util.Scanner; public class swapWithoutVariable2{ public static void main(String[] args){ int a,b; Scanner sc=new Scanner(System.in); a=sc.nextInt(); b=sc.nextInt(); a=a^b; b=a^b; a=a^b; System.out.println("a= "+a); System.out.println("b= "+b); } }

Need Help?

Looking for any Software or Tutorial?
Don't Worry, we will find it for you
Contact Now