Four ways to exchange two variables

Source: Internet
Author: User

For the exchange of two variables, I found four methods, below I use Java to illustrate.

1. Use the third variable to exchange values, a simple method.

Class Testev

Create a class

{

public static void Main (String[]args)

{

int x =5,y=10; Define two variables

int temp = x; Define the third Temp variable temp and extract the X value

x = y; Assign the value of Y to X

y = temp; Then assign the temporary variable temp value to Y

System.out.println ("x=" +x+ "y=" +y);

}

}

2. It is possible to exchange data in the same way that two numbers are summed and subtracted, and the disadvantage is that if the values of x and Y are too large, the value exceeding int will lose precision.

Class testev//Create a classes {public static void main (String[]args) {int x =5,y=10;//define two variables x = x + y        ;        X (All) = 5 + ten; y = x-y;                Y (5) = x (15)-10;        x = XY;            X (Ten) = X (All)-Y (5) System.out.println ("x=" +x+ "y=" +y); }    }

3. The use of bit operations to exchange data, The thought principle used is: a number of different or the same number two times, the result is the number , and will not exceed the int range

Class Testev

Create a class

{

public static void Main (String[]args)

{

int x =5,y=10; Define two variables

x = X^y;

y = x^y; Y= (x^y) ^y

x = X^y; x= (x^y) ^x

System.out.println ("x=" +x+ "y=" +y);

}

}

  

4. Simplest, swap variables directly at the time of printout


Class Testev

Create a class

{

public static void Main (String[]args)

{

int x =5,y=10; Define two variables

System.out.println ("x=" +y+ "y=" +x); Exchange directly at the time of output

}

}



From for notes (Wiz)

Four ways to exchange two variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.