Java three methods for exchanging values of two variables

Source: Internet
Author: User

Java exchanges the values of two variables in the following three methods:
 
1. intermedian exchange
 
Int x = 10;
Int y = 20;
Int temp = x;
X = y;
Y = temp;
 
This method can regard the intermediate amount as an empty cup, that is, to regard temp as an empty cup,
Regard x as a cup containing white wine, and regard y as a cup containing red wine.
 
Int temp = x; pour the liquor into an empty cup. At this time, temp is filled with liquor, and x is changed to an empty cup.
X = y; Pour red wine in y into x empty cup. At this time, x is filled with red wine, and y is changed to empty cup.
Y = temp; pour white wine into the empty y cup. At this time, x is filled with red wine, and y is filled with white wine to swap x and y.
 
2. addition, subtraction, and exchange of Values
 
Int x = 10;
Int y = 20;
X = x + y;
Y = x-y;
X = x-y;
 
This method calculates the sum of two numbers first and then performs the subtraction operation.
 
X = x + y; the value of x is 10 + 20 = 30;
Y = x-y; at this time, x is changed to 30 by the above calculation, so y = 30-20 = 10;
X = x-y; at this time, y is changed to 10 by the above calculation, so x = 30-10 = 20; swap two numbers
 
3. Displacement operation Switching
 
Int x = 10;
Int y = 20;
X = x ^ y;
Y = x ^ y;
X = x ^ y;

Related Article

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.