swap values of two variables without using third variable

Learn Java Programming for Beginners

Swap values of two variables in java

Using arithmetic operator to swap values of two variables without using third variable

this method is simple and easy to understand,

  1. first add the two numbers which you want to swap save new no in second variable
  2. subtract first no from second no and save in first variable.
  3. now value of a is change so again subtract first no from second no and save in second variable.
  4. print the output

import java.io.*;
class swap_values_of_two_variables_without_using_third_variable
{
public static void main(String args[])throws IOException
{
int a,b;
DataInputStream in=new DataInputStream(System.in);
System.out.print("\nEnter Value of variable A\t:");
a=Integer.parseInt(in.readLine());
System.out.print("\nEnter Value of variable B\t:");
b=Integer.parseInt(in.readLine());
b=a+b;
a=b-a;
b=b-a;
System.out.println("\nSwaping value of two variable...\n");
System.out.print("Enter Value of variable A\t:"+a+"\n\n");
System.out.print("Enter Value of variable B\t:"+b+"\n\n");
}
}

Using Logical XOR Operator to swap values of two variables without using third variable

we are using property of XOR, here a=1 and b=0

a=a ^ ((a ^ b) ^ b)=1^ ((1 ^ 0) ^ 0)
a=1^ (1 ^ 0)
a =1^ (1)
a =0
initially a was 1 but now a=0 same logic is shown below in java code..

import java.io.*;
class swap_values_of_two_variables_without_using_third_variable
{
public static void main(String args[])throws IOException
{
int a,b;
DataInputStream in=new DataInputStream(System.in);
System.out.print("\nEnter Value of variable A\t:");
a=Integer.parseInt(in.readLine());
System.out.print("\nEnter Value of variable B\t:");
b=Integer.parseInt(in.readLine());
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("\nSwaping value of two variable...\n");
System.out.print("Enter Value of variable A\t:"+a+"\n\n");
System.out.print("Enter Value of variable B\t:"+b+"\n\n");
}
}

Output
swap values of two variables without using third variable

swap values of two variables without using third variable

swap values of two variables without using third variable

Facing difficulties in understanding the program ?

Ask Your Queries in Comment Box

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *