我正在阅读一些Java文本并获得以下代码:
int[] a = {4,4};
int b = 1;
a[b] = b = 0;
Run Code Online (Sandbox Code Playgroud)
在文中,作者没有给出明确的解释,最后一行的效果是: a[1] = 0;
我不太清楚我理解:评估是如何发生的?
我在这个网站上遇到过这个问题,并在Eclipse中尝试过,但无法理解它们的评估方式.
int x = 3, y = 7, z = 4;
x += x++ * x++ * x++; // gives x = 63
System.out.println(x);
y = y * y++;
System.out.println(y); // gives y = 49
z = z++ + z;
System.out.println(z); // gives z = 9
Run Code Online (Sandbox Code Playgroud)
根据网站上的评论,x + = x ++*x ++*x ++解析为x = x +((x + 2)*(x + 1)*x),结果证明是真的.我想我错过了关于这个运算符优先级的一些东西.
我最近不得不做一个Java考试,并且想知道我遇到的一个问题.问题如下:
在没有任何参数的情况下运行以下代码将打印什么...
public class TestClass {
public static int m1(int i){
return ++i;
}
public static void main(String[] args) {
int k = m1(args.length);
k += 3 + ++k;
System.out.println(k);
}
}
Run Code Online (Sandbox Code Playgroud)
答案是1到10之间的数字.我的原始答案是7,而他们说正确答案是6.
我的逻辑:
m1 sets k to 1, as it's ++i and thus gets incremented prior to returning.
then the += is unrolled, making: 'k = k + 3 + ++k'.
++k is executed, making k 2.
Replace the variables with their value: 'k = 2 + 3 + …Run Code Online (Sandbox Code Playgroud) 以下代码打印出"3",而不是"4",如您所料.
public class Foo2 {
public static void main(String[] args) {
int a=1, b=2;
a = b + a++;
System.out.println(a);
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了.在加载"a"的值之后发生后缀增量.(见下文).
我不太明白的是为什么.postfix ++的运算符优先级高于+所以不应该先执行?
% javap -c Foo2
Compiled from "Foo2.java"
public class Foo2 extends java.lang.Object{
public Foo2();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iconst_2
3: istore_2
4: iload_2
5: iload_1
6: iinc 1, 1
9: iadd
10: istore_1
11: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
14: …Run Code Online (Sandbox Code Playgroud)