Method 1: Use an intermediate variable to exchange values.
public class JiaoHuan1{ public static void main(String[] args){ int a=5,b=10; //定义两个变量 System.out.println("交换前:"+a+"\t"+b); int t; //引入一个中间变量 //交换变量 t=a; a=b; b=t; System.out.println("交换后:"+a+"\t"+b); } }
operation result:
Method 2: Use the method of summing and subtracting two numbers for data exchange. The disadvantage is that if the values of x and y are too large, the value of int will lose accuracy.
public class JiaoHuan2{ public static void main(String[] args){ int a=5,b=10; //定义两个变量 System.out.println("交换前:"+a+"\t"+b); //交换变量 a=a+b; //a=5+10=15 b=a-b; //b=15-10=5 a=a-b; //a=15-5=10 System.out.println("交换后:"+a+"\t"+b); } }
operation result:
Method 3: Use bit operations to exchange data. The principle of the idea is that a number is XOR the same number twice, and the result is still that number, and it will not exceed the range of int.
public class JiaoHuan3{ public static void main(String[] args){ int a=5,b=10; //定义两个变量 System.out.println("交换前:"+a+"\t"+b); //交换变量 a=a^b; b=a^b; //b=(a^b)^b a=a^b; //a=(a^b)^a System.out.println("交换后:"+a+"\t"+b); } }
operation result:
Method 4: directly exchange variables when printing out
public class JiaoHuan4{ public static void main(String[] args){ int a=5,b=10; //定义两个变量 System.out.println("交换前:"+a+"\t"+b); System.out.println("交换后:"+b+"\t"+a); } }
operation result: