Swap two numbers without have a temporary variable

Swapping two number programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40. So, after swapping the value of var1 will become 40 & value of var 2 will become 20.

Program:-

package payilagam.institution;

public class Swap {

	public static void main(String[] args)
	{
         int no1 =10;  
         int no2 = 20; 
         System.out.println("Before Swapping");
         System.out.println("no1  " +no1);
 	    System.out.println("no2  "  +no2);
     
         no1 = no1+no2; 
	    no2 = no1-no2; 
	    no1 =no1 -no2; 
	    System.out.println("After Swapping");
	    System.out.println("no1  " +no1);
	    System.out.print("no2  "  +no2);
	}     
}
	

Output Screenshot:-

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free