Home >Java >Javagetting Started >What are the ways to exchange the values of two variables in java?
Method:
1. Define temporary variables
2. No need to define temporary variables
3. Use bit operators
(Learning video sharing: java course)
Code example:
public class SwapTest { public static void main(String[] args) { int num1 = 10; int num2 = 20; //方式一:定义临时变量的方式 //推荐使用方式 int temp = num1; num1 = num2; num2 = temp; System.out.println("方式一num1:"+num1); System.out.println("方式一num2:"+num2); //方式二: //好处:不用定义临时变量 //弊端:① 相加操作可能超出存储范围 // ② 有局限性:只能适用于数值类型 num1 = 10; num2 = 20; num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; System.out.println("方式二num1:"+num1); System.out.println("方式二num2:"+num2); //方式三:使用位运算符 //有局限性:只能适用于数值类型 num1 = 10; num2 = 20; num1 = num1 ^ num2; num2 = num1 ^ num2; num1 = num1 ^ num2; System.out.println("方式三num1:"+num1); System.out.println("方式三num2:"+num2); } }
Running results:
方式一num1:20 方式一num2:10 方式二num1:20 方式二num2:10 方式三num1:20 方式三num2:10 Process finished with exit code 0
Related recommendations :Getting started with java
The above is the detailed content of What are the ways to exchange the values of two variables in java?. For more information, please follow other related articles on the PHP Chinese website!