请解释这段代码我输出为6,有人请帮助我。
class A {
static int i=1111;
static {
i=i-- - --i;
}
{
i=i++ + ++i;
}
}
class B extends A {
static {
i=--i - i--;
}
{
i=++i + i++;
}
}
public class Shadow2 {
public static void main(String[] args) {
B b = new B();
System.out.println("Find->" + b.i);
}
}
输出
Find->6
任何人都可以帮我查看代码
答案 0 :(得分:0)
由于操作顺序:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
将减号放在后面就意味着先行了。
例如:
i=i-- - --i
将是:
i = i - (i-1-1)
使用打印行或单步执行并观察变量以查看每个步骤中发生的情况
答案 1 :(得分:0)
first in static A->
i=i-- - --i; will be 2 becoz, i-- means first assign value and then decrement the value so,i--=1111 then in satic memory i will be 1110 then --i means first decrement and then assign so, in this 1110 will become 1109 and then value of i wiil be 2.
secondly in static B->
currently i is 2. i=--i - i--; will be i=1-1 i will be zero
third instance block of A will be executed->
i=i++ + ++i will be i=0+2=2
finaly instance block of B will be executed->
i=++i + i++ will be i=3+3=6