Tuesday, December 13, 2011

java program for swapping two variables without using third variable

import java.util.*;
import java.io.*;
class swapping
{
public static void main(String args[])throws Exception
{

System.out.println("enter a value");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int a= Integer.parseInt(k.readLine());
System.out.println("enter b value");
int b= Integer.parseInt(k.readLine());
System.out.println("Before Swapping:");
System.out.println("a="+a+" "+"b="+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("After Swapping:");
System.out.println("a="+a+" "+"b="+b);
}
}

Output:
enter a value
3
enter b value
4
Before Swapping
a=3 b=4
After Swapping
a=4 b=3