0

Given this code:

int p,k=8;
p=k*(++k-8);
System.out.println(p);

when ++k is evaluated k=9 and then that becomes k*(9-8) giving 9*1

int p,k=8;
p=(++k-8)*k;
System.out.println(p);

But this gives 9 as output

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
  • 1
    In my IDE it prints 8 , at the end of the program `p=8` and `k=9`. @Harsh which IDE you are using ? – Khalid Shah Jan 05 '19 at 09:07
  • 2
    Precedence is not the same as evaluation order. [Java always evaluates left-to-right](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.7). Precedence specifies how those evaluations are combined. – Andy Turner Jan 05 '19 at 09:13
  • 'This' being what? A correct Java compiler should produce 8 here. You have stated you get both 8 and 9. Which is it? Unclear what you're asking. – user207421 Jan 05 '19 at 09:42
  • Possible duplicate of [If parenthesis has a higher precedence then why is increment operator solved first?](https://stackoverflow.com/questions/28219423/if-parenthesis-has-a-higher-precedence-then-why-is-increment-operator-solved-fir) – try-catch-finally Jan 06 '19 at 07:58

2 Answers2

5

You have a multiplication with

left side:  k  
right side: (++k-8)

As you correctly stated, braces have precedence. However, your program still runs "from left to right". So first the left side is evaluated, which is k = 8. Afterwards the right side is evaluated, which is (++k-8) = 1. Now we have determined both sides and can multiply them together: 8*1 = 8.

Patric
  • 1,489
  • 13
  • 28
1

this is the class file your code compiled:

   int k = 8;
    byte var10000 = k;
    int k = k + 1;
    int p = var10000 * (k - 8);
    System.out.println(p); 
宏杰李
  • 11,820
  • 2
  • 28
  • 35