Java Reference
In-Depth Information
Precedence
Level
Operator
Operation
Associates
+
-
1
unary plus
unary minus
multiplication
division
remainder
addition
subtraction
string concatenation
assignment
R to L
2
*
/
%
+
-
+
=
L to R
3
L to R
4
R to L
FIGURE 2.4
Precedence among some of the Java operators
The parentheses used in expressions are actually operators themselves. Parentheses
have a higher precedence than almost any other operator. Figure 2.4 shows a prece-
dence table with the relationships between the arithmetic operators, parentheses, and
the assignment operator. Appendix D includes a full precedence table showing all
Java operators.
For an expression to be syntactically correct, the number of left parentheses
must match the number of right parentheses and they must be properly nested.
The following examples are not valid expressions:
result = ((19 + 8) % 3) - 4); // not valid
result = (19 (+ 8 %) 3 - 4); // not valid
Keep in mind that when a variable is referenced in an expression, its current
value is used to perform the calculation. In the following assignment statement,
the current value of the variable count is added to the current value of the variable
total , and the result is stored in the variable sum :
sum = count + total;
The original value contained in sum before this assignment is overwritten by the
calculated value. The values stored in count and total are not changed.
The same variable can appear on both the left-hand side and the right-hand
side of an assignment statement. Suppose the current value of a variable called
count is 15 when the following assignment statement is executed:
count = count + 1;
 
Search WWH ::




Custom Search