Do this...
Create a test-case class named
Experiment07Test
.
So precedence (seen in the previous experiment) determines the order of evaluation in many cases, but what happens when operators with the same precedence are next? Who goes first?
Consider this expression:
8 - 4 - 2
If the leftmost subtraction is performed first, then the expression evaluates as follows:
(8 - 4) - 2 = 4 - 2 = 2
But if the rightmost subtraction is performed first, then the expression evaluates like so:
8 - (4 - 2) = 8 - 2 = 6
Give it guess, as before.
Do this...
Create a test method in Experiment07Test
named
testAssociativity()
, and add this statement:
assertEquals("8 minus 4 minus 2", ???, 8 - 4 - 2);
Replace the ??? with whatever value you think the expression should evaluate to. Then compile and run the test case for a green bar.
Once again the order in which operators are applied determines the value of the expression. However, some characteristic other than precedence must be used in a situation like this because each of the operators in question have the same precedence level.
This new characteristic is called operator associativity. Associativity describes how the compiler should parenthesize an expression when precedence has been exhausted. There are two options:
(8 - 4) - 2
8 - (4 - 2)
Question #03.07.01 Is subtraction left or right
associative? Use the results of your tests and the analysis at the
beginning of this experiment.
To be answered in Exercise
Questions/lab03.txt
.
While Java has both left and right associative operators, all arithmetic and logic operators have the same associativity.
left associative, operator associativity, right associative