-3

I know how pre and post increment operators work, but recently I found out a strange behavior in Java. What i knew so far was (as explained in this answer as well):

a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)

which clearly shows that the ++a returns the value after increment, a++ returns the value before increment. But very recently, I came across this piece of code:

int a = 0;
int b = a++;
int c = ++b;
System.out.println("b=" + b + "\nc=" + c);

The output to this piece of code is:

b=1
c=1

which is strange as a++ should return 0, and increment a, keeping the value of b to 0, as evident from the answer quoted above, while in the next line, b should be incremented first before the value is assigned to c, making it 1. What is happening here?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • exactly what you said: "b should be incremented first" - so when you print b it is 1 then "value is assigned to c" which is 1 – Vadim Oct 23 '18 at 16:53
  • 1
    _What is happening here?_ An abomination. Mixing increment (or decrement) operators with other operators is a recipe for confusion. – rgettman Oct 23 '18 at 16:53
  • 1
    Everything happens on the third line. At the start, b=0 as you say. b then is pre-incremented to 1, and 1 is assigned to c. That's it. – markspace Oct 23 '18 at 16:54
  • https://introcs.cs.princeton.edu/java/11precedence/. `++` despite looking so cool has a measly rank of 15, while `=` sits there on the top! – jrook Oct 23 '18 at 16:56

2 Answers2

4

When int b = a++ is called, the value of a (0) is assigned to b (now 0), and then a is incremented to 1.

So, when int c = ++b is called, b is 0. b is then incremented to 1 (by ++b) and then its value is assigned to c.

At the end, b=1 and c=1

pyroxian
  • 41
  • 2
2

What exactly you find as strange as it is the expected behavior...

int a = 0; // declare a
int b = a++; // declare b with the value of 0, a becomes 1 afterwards.
int c = ++b; // both c and b gets 0++ here -> 1

System.out.println("b=" + b + "\nc=" + c); prints the expected output.

b=1
c=1
dbl
  • 1,109
  • 9
  • 17
  • 1
    oh yes. I am really sorry, I was completely ignoring the fact that ++b will change the value of b as well. closing the question. my bad – Khizar Amin Oct 23 '18 at 16:58
  • I think you could delete it as it has no value for the community. – dbl Oct 23 '18 at 17:07