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