Java code to swap two numbers without using temporary variable
import java.io.*;
class Test {
public static void main(String[] args) throws IOException {
int a,b;
System.out.println("Enter first number:");
BufferedReader br1=new BufferedReader(new InputStreamReader (System.in));
a=Integer.parseInt(br1.readLine());
System.out.println("Enter second number:");
BufferedReader br2=new BufferedReader(new InputStreamReader (System.in));
b=Integer.parseInt(br2.readLine());
System.out.println("After swapping a="+a+" b= "+b);
//process one
a=b+a;
b=a-b;
a=a-b;
System.out.println("After swapping a= "+a+" b= "+b);
//process two
a=5;
b=10;
a=a+b-(b=a);
System.out.println("After swapping a= "+a+" b= "+b);
//process three
a=5;
b=10;
a=a^b;
b=a^b;
a=b^a;
System.out.println("After swapping a= "+a+" b= "+b);
//process four
a=5;
b=10;
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
System.out.println("After swapping a= "+a+" b= "+b);
}
}
No comments:
Post a Comment