Hands on Testing Java: Lab #3

Experiment #6: Operator Precedence

Do this...
Create a test-case class named Experiment06Test.

Order Matters

The arithmetic operations of addition, subtraction, multiplication and division are familiar ones. However, when these operations are mixed within an expression, some mechanism must be used to determine which operation is to be performed first. This is important because the value of the expression can change, based on the order in which operators are applied.

Consider this expression:

16 + 8 / 4

If the operations are simply performed from left-to-right (+ and then /), the expression evaluates as follows:

(16 + 8) / 4 = 24 / 4 = 6

But what's so special about the +? Let's do the division first!

16 + (8 / 4) = 16 + 2 = 18

The result of an expression thus depends on the order in which operators are applied.

Do this...
Create a test method in Experiment06Test named testPrecedence(), and add this statement:

assertEquals("16 plus 8 divided by 4", ???, 16 + 8 / 4);

Replace the ??? with whatever value you think the expression should evaluate to. Don't parenthesize the expression in the code because that's what we're trying to test! Compile and run your code for a green bar.

Operator Precedence

You might have been surprised by the result above. The division is done first because of operator precedence. Operator precedence determines the order in which operators are evaluated. Each Java operator has a precedence or priority level, and operators with higher priority levels are applied before those with lower priority levels. In Java, the precedence of the operators we have seen thus far are as follows:

Higher: () (i.e., method call, parenthesized subexpressions)
+, -, ! (i.e, the unary operators)
*, /, %
+, -
<, <=, >, >=
==, !=
&&
Lower: ||

Parentheses can be used to change the order in which operators are evaluated, with the operator in the innermost parentheses being applied first. Try it.

Do this...
Add this statement to this experiment's test method:

assertEquals("16 plus 8, divided by 4", ???, (16 + 8) / 4);

Replace ??? with the appropriate value, compile, and run for a green bar.

Confused Compilers

The Java compiler can occasionally get confused if you ignore the precedence of your operators. They can get the compiler confused so that it can't compile your code. When (not if) this happens, add parentheses. Often the compiler errors you get will be somewhat cryptic, so look for complaints about a computation involving operators. Adding some parentheses is easy to do and will fix many problems.

Terminology

operator precedence