Tuesday, May 3, 2011

How do you swap two variables in JAVA without using a third one bu using bitwise operator ?


Answer:
/*Program to swap 2 values without using the temporary variable and Arithmetic operators*/

class Swap
{
public static void main(String args[])
{
int a=1;
int b=2;
System.out.println("Before swap: a="+a+"b="+b);
a=a^b;
b=a^b;
a=a^b;
System.out.println(" After swap: a="+a+"b="+b);
}
}

Another Method

class Swap
{

  • public static void Swap()

  • {

  • int num1 = 10;

  • int num2 = 20;

  • System.out.println("Before Swapping");

  • System.out.println("Value of num1 is :" + num1);

  • System.out.println("Value of num2 is :" +num2);

  • //add both the numbers and assign it to first

  • num1 = num1 + num2;

  • num2 = num1 - num2;

  • num1 = num1 - num2;

  • System.out.println("Before Swapping");

  • System.out.println("Value of num1 is :" + num1);

  • System.out.println("Value of num2 is :" +num2);
  • }
  • }
  •  

No comments:

Post a Comment