For String
Method 1:
public class SwapWithoutThirdVar{
public static void main (String args[]){
String s1 ="one";
String s2 ="two";
s1= s1+s2;
s2 = s1.substring(0,(s1.length()-s2.length()));
s1 = s1.substring(s2.length());
System.out.println("s1 == "+ s1);
System.out.println("s2 == "+ s2);
}
}
Method 2:
public class SwapWithoutThirdVar
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = "one";
String s2 ="two";
s1=s2+s1;
s2=s1.replace(s2,"");
s1=s1.replace(s2,"");
System.out.println("S1 : "+s1);
System.out.println("S2 : "+s2);
}
}
For Integers
public class SwapWithoutThirdVar {
public static void main(String a[]){
int x = 10;
int y = 20;
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
}