First, describe
Exchange two numbers without introducing other variables, introduce a variable to mediate, and exchange two number values.
Second, the 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 (A, B), Swapbyself (A, B);//The value is passed here, just copy a A, B copy to participate in the operation of the function, does not affect the original values of A and B in the main function System.out.println ("Main function:a=" +a+ ", b=" +b);} private static void Swapbyself (int a, int b) {//Exchange two numbers without introducing other variables, make a = A+b using the sum of two numbers; A holds two numbers and B = a-b;//Two and-B, which is AA = a-b;//Two and-B, at which point B has become a, so it is equivalent to Sum-a=bsystem.out.println ("Swapbyself first function:a = "+a+", b= "+b);//There is another way to use the difference of two numbers, that is, the distance between two numbers a = b-a; A= the difference between b = b-a;//b = The original B-two number of distance = = The original AA = a+b;//The difference between the final a= and the original a== the original BSystem.out.println ("Swapbyself second function:a=" +a+ ", b=" +b);//change back}private static void swapbyextravariable (int a, int b) {//introduce a variable to do mediation, exchange two number int temp = A;a = B;b = Temp;s Ystem.out.println ("swapbyextravariable function:a=" +a+ ", b=" +b);}} </span>
iii. Results of Operation
Java (Introducing an intermediate variable, without introducing intermediate variables) to exchange the values of two variables