Exchange the value between two variables without using a temporary variable

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

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>