Understanding the output of an arithmatic expression

后端 未结 2 1526
-上瘾入骨i
-上瘾入骨i 2021-01-27 09:24

I have a java class as follows:

class A{
    public static void main(String[] args){
       int a=10;
       a*=a++ +a;
       System.out.println(a);
    }
}

Ou         


        
相关标签:
2条回答
  • 2021-01-27 09:47

    Consider 15.7.1. Evaluate Left-Hand Operand section of java specs where it says - First, the left-hand operand is evaluated to produce a variable then the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator

    In your case it is a = 10 * ((11)+10) = 201

    0 讨论(0)
  • 2021-01-27 09:53

    In any statement of the type:

    x *= y;
    

    The initial value of the LHS is evaluated before the RHS. So your statement:

    a *= a++ + a;
    

    Is equivalent to:

    a = a * (a++ + a);
    

    Which sets a to the value 10 * (10 + 11) => 210.

    If you're particularly interested in the formal specification related to this point you can find it here which contains the rule "If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation."

    0 讨论(0)
提交回复
热议问题