Shortest way to swap two number in java

Here is the shortest way to swap two numbers in java.
 
we can swap two numbers just by using a single line of code.

First of all, let me clear what is the mean of swapping numbers?

suppose we have two var, 

 int x = 10;
 int y = 25; 

but when going to print or want to perform some action I need to swap the value like this,

 x = 25;
 y = 10; 

so to perform this thing we have so many algorithms are there, I'm going to share the shortest or we can say the easiest way to swap two numbers.

public class JavaOneWorld {
    public static void main(String args[]) {
      int x=10;
      int y=25;
      System.out.println("Before Swap: value of x= "+x+" value of y= "+y);

      y = x-y+(x=y);
      
     //or

     // y = x+y-(x=y); //this line will also produce same output.

   

      System.out.println("After Swap: value of x= "+x+" value of y= "+y);
    }
}

No comments:

Post a Comment