Easy tech stuff!

Exchange the value between two variables without using a temporary variable

Posted: January 31st, 2008 | Author: Nischal Shetty | Filed under: General | Tags: , , | No Comments »

Let me show you how you can interchange the values stored in two variables without using a temporary variable.

Case 1: For two integers

int a = 10;

int b = 20;

a = a+b;

b = a-b;

a = a-b;

Thats all!!! When you print the values stored in these two variables, you’ll notice that the values have been interchanged!

Case 2 : For two Strings

String s1 = “Shetty”;
String s2 = “Nischal”;

s1 = s1+s2;
s2 = s1.substring(0,s1.length()-s2.length());
s1 = s1.substring(s2.length());

System.out.println(“My name is “+s1+” “+s2);

The output will be: My name is Nischal Shetty

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png


Leave a Reply