Common method, advanced method, great God method
1 @Test2 Public voidtest3 () {3 intm = 5;4 intn = 12;5 6 //requires M and N swap locations7System.out.println ("m=" + M + "n=" + N);//m=5 n=128 9 //method One: Define temporary variablesTen //Advantages: Simple operation, disadvantage: need to define temporary variables, memory consumption is large One inttemp =m; Am =N; -n =temp; -System.out.println ("m=" + M + "n=" + N);//m=12 n=5 the - //method Two: Do not define temporary variables, use Add - //Pros: Save memory by not having to define temporary variables. Cons: Easy to lose accuracy when two values are large -m = m + N;//5 + +n = m-n;//12 + 5-5, is the value of the original m, assigned to n -m = m-n;//12 + 5-12, is the value of the original N, assigned to M +System.out.println ("m=" + M + "n=" + N);//m=5 n=12 A at //Method Three: Dedicated to the gods, using XOR or ^ - //Advantages: No loss of precision, no definition of variables, memory consumption is minimal, disadvantage: ordinary people will not think so write, write the General people also can not understand -m = m ^N; -n = m ^ n;//m ^ n ^ n = = M -m = m ^ n;//m ^ n ^ m = = N -System.out.println ("m=" + M + "n=" + N);//m=12 n=5 in -}
Method Two is not recommended because it is possible to lose precision
Java implements two int number exchanges