swapping of two numbers in java all possible models

swapping of two numbers in java all possible models

MODEL:1
/*Program to swap 2 values with third variable temp*/

class Swap 

public static void main(String args[]) 

     int a=1; 
     int b=2; 

     int temp=0;
     System.out.println(“Before swap: a=”+a+”b=”+b); 
     temp=a; 
     a=b; 
     b=temp; 
     System.out.println(” After swap: a=”+a+”b=”+b); 

} 

MODEL:2

/*Program to swap 2 values with out using third variable temp*/

class Swap 

public static void main(String args[]) 

     int a=1; 
     int b=2; 

     int c=0;
     System.out.println(“Before swap: a=”+a+”b=”+b); 
     c=a; 
     a=b; 
     b=c; 
     System.out.println(” After swap: a=”+a+”b=”+b); 

} 

MODEL:3

/*Program to swap 2 values without using the temporary variable and Arithmetic operators*/ 
class Swap 

public static void main(String args[]) 

     int a=1; 
     int b=2; 
     System.out.println(“Before swap: a=”+a+”b=”+b); 
     a=a^b; 
     b=a^b; 
     a=a^b; 
     System.out.println(” After swap: a=”+a+”b=”+b); 



MODEL:4

/*Program to swap 2 values without using the temporary variable and third variable*/ 

class Swap
{
public static void Swap()

{

      int a=1; 

      int b=2; 

      System.out.println(“Before swap: a=”+a+”b=”+b); 
     
      //add both the numbers and assign it to first

      a=a+b; 

      b=a-b; 

      a=a-b; 

     System.out.println(” After swap: a=”+a+”b=”+b); 

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: