Next: Definition of constants and Up: Unit 04 Previous: Increment and decrement operators

## Expressions with side-effect and statements (optional)

Java uses the term expression to indicate two different notions:

• those expressions whose only effect is the calculation of a value, such as the expressions of type int, which can be composed according to the rules of arithmetics;
• those expressions that, besides calculating a value, correspond to an operation on memory, such as an assignment (simple or combined) or an increment. We call these expressions-with-side-effect. Recall that we use the term side-effect to indicate a modification of the state (i.e., the memory) of the program. Expressions of this type can be transformed into statements by ending them with ``;'', and this is exactly what we have done till now to assign a value to (or increment/decrement) variables. By transforming an expression-with-side-effect into a statement, we give up considering it an expression that has an associated value.

Example:

• 23*x+5 is a mathematical expression;
• x = 7 is an expression-with-side-effect that is valid in Java and whose value is (the right hand side of the assignment). If we end them with ``;'' we obtain the statement x = 7;
• y = x = 7 is also a valid Java expression, which has two side-effects: the first one assigns 7 to x, while the second one assigns the value of the expression x = 7 (which, as said, is 7) to y.

While Java allows us to use both types of expressions without limitations, we will use expressions-with-side-effect only to form statements, and we will always avoid their use inside arithmetic expressions.

Example: The statement

```x = 5 * (y = 7);
```
should be rewritten as follows:
```y = 7;
x = 5 * y;
```

This distinction is motivated by the fact that expressions are an abstraction for the mathematical concepts of function and of function application, while expressions-with-side-effect (statements) are an abstraction for the concept of assignment, i.e., of the modification of a memory location of the program.

Next: Definition of constants and Up: Unit 04 Previous: Increment and decrement operators