a += a++ * a++ * a++ in Java. How does it get evaluated?

前端 未结 6 605
旧时难觅i
旧时难觅i 2020-12-10 15:27

I came across this problem in this website, and tried it in Eclipse but couldn\'t understand how exactly they are evaluated.

    int x = 3, y = 7, z = 4;

          


        
6条回答
  •  鱼传尺愫
    2020-12-10 15:52

    Java evaluates expressions left to right & according to their precedence.

    int x = 3, y = 7, z = 4;
    
    x (3) += x++ (3) * x++ (4) * x++ (5);  // gives x = 63
    System.out.println(x);
    
    y = y (7) * y++ (7);
    System.out.println(y); // gives y = 49
    
    z = z++ (4) + z (5);
    System.out.println(z);  // gives z = 9
    

    Postfix increment operator only increments the variable after the variable is used/returned. All seems correct.

    This is pseudocode for the postfix increment operator:

    int x = 5;
    int temp = x;
    x += 1;
    return temp;
    

    From JLS 15.14.2 (reference):

    The value of the postfix increment expression is the value of the variable before the new value is stored.

提交回复
热议问题