Java: pre-,postfix operator precedences

前端 未结 5 670
-上瘾入骨i
-上瘾入骨i 2020-12-03 14:41

I have two similar questions about operator precedences in Java.

First one:

int X = 10;
System.out.println(X++ * ++X * X++); //it pr         


        
5条回答
  •  无人及你
    2020-12-03 15:17

    First step

    1) first postfix operator: X++ 
       1.a) X++ "replaced" by 10
       1.b) X incremented by one: 10+1=11
       At this step it should look like:  System.out.println(10 * ++X * X++), X = 11;
    
    2) prefix operator: ++X
       2.a) X "replaced" by 11
       2.b) X incremented by one: 11+1=12
       At this step it should look like:  System.out.println(10 * 12 * X++), X = 12;
    
    3) second POSTfix operator: X++
       3.a) X "replaced" by 12
       3.b) X incremented by one: 12+1=13
       At this step it should look like:  System.out.println(10 * 12 * 12),  X = 13;
    

    This prints 10 * 12 * 12 = 1440

    This is the bytecode for the first step

     1. bipush 10
     2. istore_0
     3. getstatic java/lang/System/out Ljava/io/PrintStream;
     4. iload_0
     5. iinc 0 1
     6. iinc 0 1
     7. iload_0
     8. imul
     9. iload_0
    10. iinc 0 1
    11. imul
    12. invokevirtual java/io/PrintStream/println(I)V
    13. return
    

    This do the following:

     1. Push 10 to the stack
     2. Pop 10 from the stack to X variable
     3. Push X variable value (10) to the stack
     5. Increment local variable X (11)
     6. Increment local variable X (12)
     7. Push X variable value (12) to the stack
     8. Multiply top and subtop (10*12) Now Top = 120 
     9. Push X variable value (12) to the stack
    10. Increment local variable X (13)
    11. Multiply top and subtop (120*12) Now Top = 1440
    

    Notice than the last increment (10.) is done after the push of X to the stack

提交回复
热议问题