Chapter 3: Conditions with Side Effects

In Java, it is legal to nest assignments inside test conditions:
if ((d = b * b – 4 * a * c) >= 0) r = Math.sqrt(d);
It is legal to use the decrement operator inside other expressions:
if (nā€“ā€“ > 0) . . .
These are bad programming practices because they mix a test with another activity. The other activity (setting the variable d, decrementing n) is called a side effect of the test.
Conditions with side effects can occasionally be helpful to simplify loops; for if statements they should always be avoided.

Occasionally all the work of a loop is already done in the loop header. Suppose you ignore good programming practices and write an investment doubling loop as follows:
for (years = 1;
(balance = balance + balance * rate / 100) < targetBalance; years++);
System.out.println(years);
The body of the for loop is completely empty, containing just one empty statement terminated by a semicolon.
If you do run into a loop without a body, it is important that you make sure the semicolon is not forgotten. If the semicolon is accidentally omitted, then the next line becomes part of the loop statement!
for (years = 1;
(balance = balance + balance * rate / 100) < targetBalance; years++)
System.out.println(years);
You can avoid this error by using an empty block { } instead of an empty statement.