Java Language Pitfall: combining assignment and side-effects


Occasionally we see StackOverflow Java questions (and C or C++ questions) that ask what something like this:

i += a[i++] + b[i--];

evaluates to ... for some known initial states of i, a and b.

Generally speaking:

  • for Java the answer is always specified1, but non-obvious, and often difficult to figure out
  • for C and C++ the answer is often unspecified.

Such examples are often used in exams or job interviews as an attempt to see if the student or interviewee understands how expression evaluation really works in the Java programming language. This is arguably legitimate as a "test of knowledge", but that does not mean that you should ever do this in a real program.

To illustrate, the following seemingly simple example has appeared a few times in StackOverflow questions (like this one). In some cases, it appears as a genuine mistake in someone's code.

int a = 1;
a = a++;
System.out.println(a);    // What does this print.

Most programmers (including Java experts) reading those statements quickly would say that it outputs 2. In fact, it outputs 1. For a detailed explanation of why, please read this Answer.

However the real takeaway from this and similar examples is that any Java statement that both assigns to and side-effects the same variable is going to be at best hard to understand, and at worst downright misleading. You should avoid writing code like this.

1 - modulo potential issues with the Java Memory Model if the variables or objects are visible to other threads.