-1

According to https://introcs.cs.princeton.edu/java/11precedence/

++ is higher priority than =

But the code below. count prints out 0 instead of 1.

I thought int count = F[0]++;,

  1. get the value of F[0]

  2. ++ is applied to this value 0 which becomes 1

  3. then this increased value is assigned to count.

But it's not. To print out 1, should be int count = ++F[0];

OMG, have I misunderstood embarrassingly such extremely basic thing for a long time? This is 101 for a freshman in college question, but can someone please let me why this prints out 0 instead of 1?

        int[] F = new int[26];
        int count = F[0]++;
        System.out.println(count);      // count is 0  (instead of 1) !!!

user2761895
  • 1,431
  • 4
  • 22
  • 38
  • 2
    Yes, but `++` operator os post-incrementation, so it's job is NOT to get the value after computation – azro Dec 21 '19 at 22:31
  • i = 0; `int a = i++` will set `a` to `0`. `int a = ++i` will set `a` to `1`. First one is post-increment which happens after statement completion. and second is `pre-increment` which happens before statement completion. – Sunil Dabburi Dec 21 '19 at 22:33

1 Answers1

1

The assignement happens before the post-increment - that's why it's called post-increment. Therefore count becomes 0 but if you print out F[0], its value would be 1.

int[] F = new int[26];       // F[0] is 0 (default value)
int count = F[0]++;          // F[0] is 0, 
                             // then count = F[0], therefore count = 0
                             // then F[0] is 1 (post-incremented)
System.out.println(count);   // count is not affected and remains 0
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • This isn't technically true; the code `int y = x++;` compiles to `iload_1`, `iinc 1, 1`, `istore_2`, so the increment happens before the store. It's just that the store uses the value which was loaded by `iload_1` before the increment occurs. – kaya3 Dec 21 '19 at 22:45
  • Yeah, I was describing from an observation of a developer side. I have no clue about the compiled bytecode. Thanks for a lesson :) – Nikolas Charalambidis Dec 21 '19 at 22:46
  • 1
    Sure! In practice it only makes a difference for tricky code like `int y = (x++) + (x++);` where the first increment has its effect before the second increment is performed, so if `x` starts as 0 then the value of the first `x++` is 0 and the value of the second is 1, leaving y = 1. That shows that the value of x has changed before y gets assigned, but it's better not to write code like this anyway. – kaya3 Dec 21 '19 at 22:53
  • Thanks @kaya3 your answer what I needed. – user2761895 Dec 21 '19 at 22:57
  • @Andreas: A typo fixed. :) – Nikolas Charalambidis Dec 21 '19 at 23:36