Java Reference
In-Depth Information
Continued
Category
Operators
logical OR
||
ternary
? :
assignment
= += -= *= /= %= &= ^= |= <<= >>= >>>=
Operator Precedence
The first thing to know about operators is that they have precedence. I can't forget Mr. Smith in junior
high algebra class teaching us to memorize Please Excuse My Dear Aunt Sally. That odd phrase is an
effective mnemonic for the order of operations (another name for operator precedence) in algebra. It
shortens to PEMDAS, which gives us Parentheses, Exponent, Multiplication,Division, Addition, and
Subtraction. Thanks to operator precedence (and, in my case, Mr. Smith), when we work with algebra
equations, we know to resolve parentheses before we resolve exponents, exponents before
multiplication, and so on.
The same kind of thing holds true in Java (and many other programming languages). However, as
shown previously, Java has a lot more than six operators. Also, Java has some operators that have the
same level of precedence. In those cases, precedence proceeds from left to right for binary operators
(except assignment operators) and right to left for assignment operators. That's probably as clear as
mud, but we get to some examples shortly that clarify the order of operations and identify some of the
problem spots where people often trip.
The Missing Operator: Parentheses
Parentheses aren't in the list of Java operators, but they act as an operator with the highest precedence.
Anything in parentheses is resolved first. When a line has several sets of parentheses, they are resolved
from innermost to outermost and from left to right. Let's consider some examples in Listing 4-1.
Listing 4-1. Parentheses as an operator
System.out.println(2 + 4 / 2); // division processed first, so prints 4
System.out.println((2 + 4) / 2); // addition processed first, so prints 3
System.out.println((2 + 4) / 3 * 2); // prints 4, not 1 - see below for why
System.out.println((2 + 4) / (3 * 2)); // prints 1
System.out.println((2 + 4) / (2 * 2)); // prints 1 - note the truncation
System.out.println((2.0 + 4.0) / (2.0 * 2.0)); // prints 1.5
The bolded line prints 4 because the division operator gets processed before the multiplication
operator. That happens because operators of equal precedence get processed from left to right. In
algebra, multiplication comes before division. However, Java is not algebra, and that sometimes trips up
new Java developers who remember their algebra. (I've tripped over that difference at least once.)
Search WWH ::




Custom Search