When we start combining operators, variables and/or method invocations into valid pieces of code that return a value, we start constructing what are called expressions.
All expressions return a value, and the type of the value that is returned will depend on the elements it is constructed from. For example, we can have a boolean expression, like
age >= 18, an int expression
2 + 3, etc.
An Expression is not a Statement (although some can be!)
Expressions on their own will not compile, but are the building blocks of statements which we’ll cover in the next section. Some types of expressions however, when followed by a semicolon
(;) become statements that compile correctly.
Example 1: Valid expression, but compilation error
2 + 3
From the arithmetic operators section, we know that the above expression is valid and will return the number 5. However, as an expression
2 + 3 is valid, but it won’t compile on its own.
If you place this in a single line in your Java code on its own, you’ll get a compilation error
error: not a statement from the Java compiler.
Note that the expression is valid though, but will only compile if used as the building block of some other code.
Example 2: Valid expression and valid statement
int a; a = 2 + 3;
In this case, we have a compound expression, made up of 2 smaller expressions, the arithmetic operation
2 + 3 we saw in example 1 and an assignment operation that will cause variable
a to have a value of
When followed by a semi-colon
(;), this expression becomes an
expression statement that can be compiled and executes correctly in Java.
Expressions can be compounded
As seen in example 2, when joining together smaller expressions, we can create compound expressions as long as they use the same data type, for example:
1 * 2 + 3 * 4
These compound expressions will be executed based on the precedence of the operators used in the expression. Operators with higher precedence will be evaluated first.
It is good practice to clarify the order of execution in compound expressions by making use of parenthesis, for example:
1 * (2 + 3) * 4
The first expression
1 * 2 + 3 * 4 will yield a result of 14, whereas the second expression
1 * (2 + 3) * 4 will yield a result of 20.