The statements in the previous post perform simple calculations, but what if you want to make more complex calculations using several operations, say you want to invent a new handle on reality. Let’s say you want to create a new concept called Der kranke Monde. To find the value of this concept, you get the percentage of phyla that have pit eyes, multiply it by the area pit eyes take up in micrometers, and you add this to the time in years since proto-eyes evolved multiplied by the number of main phyla with over 96% complex eyes plus the degree of arc in stemmata multiplied by the factor by which such simple eyes’ sensitivity increases at night. To calculate the Der kranke Monde, you use this expression:
.85 of phyla have pit eyes * 100 micrometers + 600 million years * 6 phyla + 4 degree * 1000 factor increase in sensitivity
Ignoring the fact that the value of this concept as the limit of Mind approaches humans equals 0, in which order should the computer do the calculation? If the value of the expression were calculated from left to right, then the result would be
Clearly, this is not how we defined Der Kranke Monde. To calculate the correct value, the multiplications should be performed first, then the additions. This, in fact, is the order in which Java will calculate the preceding expression.
The Java compiler follows a set of rules called operator precedence to determine the order in which the operations should be performed.
The table below provides the order of precedence of the operators we’ve discussed so far. The operators in the first row—parentheses—are evaluated first, then the operators in the second row (*, /, %) are evaluated, and so on with the operators in each row. When two or more operators on the same level appear in the same expression, the order of evaluation is left to right, except for the assignment operator (=), which is evaluated right to left. As we introduce more operators, we’ll add them to the Order of Precedence chart.
Now we calculate correctly:
As you can see, 8500 could be a concept, 3600000000 another, and 4000 yet another.
We could also use parentheses to clearly display the order of calculation. For example,
The result is the same.
It sometimes helps to use parentheses to clarify the order of calculations, but parentheses are essential when your desired order of evaluation is different from the rules of operator precedence. For example, to calculate the value of this formula:
you could write this code:
This would generate incorrect results because, according to the rules of precedence, x/2 would be calculated first, then the result of that division would be multiplied by y. In algebraic terms, the preceding statement is equivalent to
To code the original formula correctly, you need to use parentheses to force the multiplication to occur before the division: