There's a lengthy chapter in the Java Language Specification on expressions, covering many cases that would be interesting only to language lawyers. What it boils down to is that an expression is any of the alternatives shown in Table 7-2.
Table 7-2. Expressions in Java
Expression |
Example of expression |
---|---|
A literal |
|
this object reference |
|
A field access |
|
A method call |
|
An object creation |
|
An array creation |
|
An array access |
|
Any expression connected by operators |
|
Any expression in parens |
|
You evaluate an expression, to get a result that will be:
A variable (as in evaluating this
gives you an object you can store into), or
A value, or
Nothing (a void expression). You get nothing as the result when you call a method with a return value of void.
An expression can appear on either side of an assignment. If it is on the left-hand side of an assignment, the result designates where the evaluated right-hand side should be stored. Here's an example:
myArray[i][j] = now.hh + 12;
The expression on the lefthand side of the assignment is evaluated, meaning that we take the name myArray, calculate index i, go to that element, take the array reference there, calculate index j, go to that element, and that place is where we will store the result that we will get from evaluating the expression on the righthand side.
The type of an expression is either known at compile time or checked at run-time to be compatible with whatever you are doing with the expression. There is no escape from strong typing in Java.
Here's an example of an expression whose type is not known until run-time. We know o
is an object, but we don't know what type it actually holds.
Object o;
if (Math.random() > 0.5)
o = new int[7];
else o = new String("surprise!");
3.22.181.47