【问题标题】:I cant able to understand this code i am getting 6 as output?我无法理解这段代码,我得到 6 作为输出?
【发布时间】:2023-11-27 09:32:02
【问题描述】:

请解释一下这段代码,我得到的输出是 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

谁能帮我看一下代码

【问题讨论】:

  • 使用调试器,您可以在运行时检查每个表达式。
  • @paxdiablo Java 中没有未定义的行为。求值顺序是严格定义的(主要是从左到右),单个语句中多次修改的效果是严格定义的(虽然我不记得它是怎么定义的了)。

标签: java shadow


【解决方案1】:
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

【讨论】: