第一次
public static void main(String[] args) {
int x = 5,y = 4;
y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
}
编译后结果
all 1 5
first 1 4
second 1 5
第二次
public static void main(String[] args) {
int x = 5,y = 4;
x^=y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
a^=b;
System.out.println("Third "+a +" " + b);
}
编译结果
all 0 5
first 1 4
second 1 5
Third 4 5
public static void main(String[] args) {
int x = 5,y = 4;
y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
}
编译后结果
all 1 5
first 1 4
second 1 5
第二次
public static void main(String[] args) {
int x = 5,y = 4;
x^=y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
a^=b;
System.out.println("Third "+a +" " + b);
}
编译结果
all 0 5
first 1 4
second 1 5
Third 4 5
解决方案 »
- StringTokenizer 竖线问题
- 关于 JNLP API 的一个超简单问题
- 调查:请问各位Java Developer中有多少人在经常使用Java泛型
- 编码解码问题
- 如何调用数据库过程?(急,在线)
- 有谁愿意跟我一起讨论使用JAVA开发移动短信平台?QQ:17088953.
- 高分在线,谁能帮我解决,我把所有的分都奉献出去!!!java 转换中的中文问题
- String的问题(split)
- 占用一下,小弟想到深圳发展,有一年JAVA开发经验,熟悉oracle数据库,哪位在深圳的兄弟帮忙介绍个工作,我的QQ:9182647,谢谢了!
- JAVA
- 能给我说一下编程语言吗
- 关于匿名内部类实现构造器的疑问
这样做是不正确的。
跟java 的表达式提取规则有关。
推荐参考一下The Java Puzzlers这本书吧
上面讲的很详细,我就没有必要再写一遍了。
推荐你看一下我说的那本书,上面有这个例子。
最好自己动手,看看bytecode怎么回事。
public class CleverSwap { public static void main(String[] args) { int x = 1984; // (0x7c0) int y = 2001; // (0x7d1) x ^= y ^= x ^= y; System.out.println("x = " + x + "; y = " + y); }}
// The actual behavior of x ^= y ^= x ^= y in Javaint tmp1 = x; // First appearance of x in the expressionint tmp2 = y; // First appearance of yint tmp3 = x ^ y; // Compute x ^ yx = tmp3; // Last assignment: Store x ^ y in xy = tmp2 ^ tmp3; // 2nd assignment: Store original x value in yx = tmp1 ^ y; // First assignment: Store 0 in x