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);
    }
}

3 comments:


  1. Customizing your belongings has never been easier with high-quality uv dtf sticker options available online. These stickers offer durability and vibrant colors, making them perfect for personal or business use. Whether you're decorating your laptop, phone, or creating unique branding, the possibilities are endless. For those looking to add a professional touch, exploring the range of UV DTF stickers can be a game-changer. Check out the website for more details on how to elevate your design projects.

    ReplyDelete