Java How to Exchange the value method of these two variables introduction _java

Source: Internet
Author: User
1. With the help of intermediate quantity Exchange
int x = 10;
int y = 20;
int temp = x;
x = y;
y = temp;

This method can be regarded as an empty cup, that is, the temp as an empty cup,
Think of X as a cup with white wine, and Y as a cup with red wines.

int temp = x; Pour white wine into an empty cup, at which time temp is filled with white wine and X becomes an empty cup.
x = y; Pour the red wine in Y into the X-Empty cup, when x is filled with red wine, and y turns into an empty cup.
y = temp; Pour white wine into Y empty cup, at this time x contains red wine, y with white wine, realize X and Y interchange

2. Numerical Add and subtract exchange
int x = 10;
int y = 20;
x = x + y;
y = x-y;
x = XY;

This method is calculated by first obtaining two numbers and then reducing the operation

x = x + y; The value of x at this time is 10+20=30;
y = x-y; At this point the X is converted to 30 by the above operation, so y = 30-20 = 10;
x = XY; At this point the Y is converted to 10 by the above operation, so x = 30-10 = 20, and a two-number interchange is achieved

3. Displacement Operation Exchange

int x = 10;
int y = 20;
x = x ^ y;
y = x ^ y;
x = x ^ y;

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.