How do I swap two string variables in Java without using a third variable, i.e. the temp variable?
String a = \"one\"
String b = \"two\"
String temp = null;
temp
String a="one";
String b="two";
a = a.concat("#" + b);
b = a.split("#")[0];
a = a.split("#")[1];
This will work as long as your string doesn't contain the # character in them. Feel free to use any other character instead.
You could use a possible Unicode character, like "\u001E" instead of the #.
public class SwapStringVariable {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "test";
String b = "paper";
a = a + b;
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length(), a.length());
System.out.println(a + " " + b);
}
}
Do it like this without using a third variable:
String a = "one";
String b = "two";
a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());
System.out.println("a = " + a);
System.out.println("b = " + b);
String a = "one";//creates "one" object on heap
String b = "two";// creates "two" object on heap
System.out.printf("a is %s , b is %s%n",a,b);
a = "two";// will not create new "two" object & now a is pointing to "two" object
b = "one";// will not create new "one" object & now b is pointing to "one" object
System.out.printf("a is %s , b is %s%n",a,b);
You can do in this way.
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "one";
String b = "two";
System.out.println(a);
System.out.println(b);
a = a+b;
b = "";
System.out.println("*************");
b = a.substring(0, 3);
a = a.substring(3, 6);
System.out.println(a);
System.out.println(b);
}
You can also do this by using a temp variable but in a different way:
String a = "one"
String b = "two"
String temp = null;
temp=a.concat(b);
b=temp.substring(0,a.length());
a=temp.substring(a.length(),temp.length());
System.out.println("After Swapping A:"+a+"B:"+b);