1.用两个数求和然后相减的方式进行数据交换。但如果x和y的数值过大,它们的和超出int的取值范围,将会损失精度,也就不能准确的成功交换数据了。
public class Test {
public static void main(String[] args) {
int x = 5;
int y = 10;
x = x + y;
y = x - y;
x = x - y;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
2.用位运算的方式进行数据的交换,因为一个数异或同一个数两次,结果还是那个数,而且不会超出int范围。
public class Test {
public static void main(String[] args) {
int x = 5;
int y = 10;
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}