Java (introduce an intermediate variable, do not introduce the intermediate variable) exchange the values of two variables, java Variables

Source: Internet
Author: User

Java (introduce an intermediate variable, do not introduce the intermediate variable) exchange the values of two variables, java Variables

I. Description

If no other variables are introduced, two numbers are exchanged, and a variable is introduced as an intermediary to exchange the values of the two numbers.

Ii. Source Code

<Span style = "font-size: 18px;"> package tong. yue. sort; public class SwapTwoValues {/*** @ param args */public static void main (String [] args) {int a = 10, B = 20; swapByExtraVariable (, b); swapBySelf (a, B); // here the value is passed, just copying a copy of a and B to participate in the function operation, does not affect the original values of a and B in the main function. out. println ("main function: a =" + a + ", B =" + B);} private static void swapBySelf (int a, int B) {// exchange two numbers without introducing other variables, and use the sum of the two numbers for a = a + B; // a to save the sum of the two numbers B = a-B; // The sum of the two numbers-B, that is, aa = a-B; // the sum of the two numbers-B. At this time, B has become a, so it is equivalent to sum-a = bSystem. out. println ("swapBySelf first function: a =" + a + ", B =" + B); // another method is to use the difference between two numbers, that is, the distance between two numbers a = B-a; // a = the difference between the two B = B-; // B = the distance between the original two numbers of B = the original aa = a + B; // The final a = the difference between the two + the original a = the original bSystem. out. println ("swapBySelf second function: a =" + a + ", B =" + B); // returns} private static void swapByExtraVariable (int a, int B) {// introduce a variable for mediation and exchange two numbers: int temp = a; a = B; B = temp; System. out. println ("swapByExtraVariable function: a =" + a + ", B =" + B) ;}</span>

Iii. Running results


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.