Expressions and Operator Precedence in Evaluation
Simple and complex expressions and their variables and operators
Expressions are combinations of variables and operators, or method invocations that follow the Java Syntax. Expressions may be simple or complex. Complex expressions use many variables and operators. Following are some examples of expressions:
x = y + 10
y = z * x
energy = mass * c * c
v = u + a*t
discriminant = b*b - 4*a*c
int i = 0
System.out.println("Hello There")
if (x == y) i = j
As you can see, expressions may contain many operators. Suppose i contains 2, j contains 3, and k contains 4. Does i + j * k evaluate to 20 (addition performed first), or 14 (multiplication performed first)? The following table shows the precedence given to different operators in Java; operators that are higher up in the table have precedence over those in the lower rows. The operator with precedence is always executed first.
|
expr++, expr-- |
|
unary operators - ++expr, --expr, +expr, -expr, ! |
|
multiplicative - *, /, % |
|
additive - +, - |
|
relational - <, >, >=, <=, instanceof |
|
equality - ==, != |
|
logical AND - && |
|
logical OR - || |
|
assignment - =, +=, -=, *=, /=, %=, &=, ^=, |= |
From the table, we can see that the example 'i + j * k' would evaluate to fourteen rather than 20 as multiplicative operators have precedence over additive operators. Brackets may be used to manually set precedence or make expressions clear in the following way:
x + y / 100 - unclear (x + y) / 100 - clarity through the use of brackets i + j * k - unclear (i + j) * k - clarity through the use of brackets
Statements are similar to expressions. A single statement forms a unit of execution, while many expressions may constitute a single statement. A statement is a line of Java code that ends with a semicolon ';'. Expressions become Expression Statements by adding a semicolon
Lines that contain variable declarations are called Declaration Statements while Control Flow Statements manage the number of times or order in which sets of statements called Blocks are executed.