Expression Statements are statements that are executed by simply evaluating the expression they contain and discarding the result. Expressively, they are a means of instructing the runtime to compute an expression (usually with side-effects).
There are a number of expressions that can be made into a statement
simply by suffixing them with a semicolon (;
). These
expressions are called Statement Expressions. An Expression Statement
is one of the statements made from these Statement Expressions. For
example,
x++
- Statement Expression
x++;
-
Expression Statement (made of a Statement Expression followed by ;
).
Expression Statements can be expressed through:
1 | stmt-expression ; |
where...
stmt-expression | is either:
|
1 An expression statement.
There are a number of expressions that may be computed as a statement, with the result simply discarded. These are known as Statement Expressions.
Expressions can only be written inside statements.
An example of this is as follows:int x = 5 + 5;
The expression 5 + 5
can be written within a local
variable declaration statement.
Certain types of expressions can have side-effects, meaning they can affect the state of the running program other than by what they evaluate to. For example,
int x = 10;
int i = 1 + x; // 1 + x evaluates to 11, so i is set to 11.
int j = ++x; // ++x evaluates to 11, so j is set to 11.
// However, ++x also changes the value of x to 11. This is a side-effect of the ++ operator.
System.out.println(x); // Prints 11
Because of side-effects, expressions can have usefulness in contexts other than within most statements. For example, a developer may want to increment a variable, which can be done using an increment expression. For example:
int x = getSomeValue();