需要第三方变量
1.通过第三方变量的方式
开发中推荐这种方式
public static void main(String[] args) {
int x = 1;
int y = 2;
int temp;
temp = x;
x = y;
y = temp;
System.out.println("x = "+x+",y = "+y);
}
结果:
不需要第三方变量
2.使用运算的方式
public static void main(String[] args) {
int x = 1;
int y = 2;
x = x + y; //此时 x = 2+1 = 3;
y = x - y; //此时 y = 3-2 = 1;
x = x - y; //此时 x = 3-1 = 2;
System.out.println("x = "+x+",y = "+y);
}
结果:
注意:此种方式存在弊端,当两个数相加的和大于int(数据类型)的取值范围时,结果有可能就会不正确。
3.使用位异或的方式(面试)
原理:一个数对另一个数位异或两次,该数本身不变
public static void main(String[] args) {
int x = 1;
int y = 2;
x = x ^ y; //此时 x = x^y;
y = x ^ y; //此时 y = 1^2^2 = 1;
x = x ^ y; //此时 x = 1^2^1 = 2;
System.out.println("x = "+x+",y = "+y);
}
结果:
总结:
开发中常用第一种通过第三方变量的方式