Expressions in Java are the primary construct for doing calculations. Here are some examples:
1 // A simple literal is an expression
1 + 2 // A simple expression that adds two numbers
(i + j) / k // An expression with multiple operations
(flag) ? c : d // An expression using the "conditional" operator
(String) s // A type-cast is an expression
obj.test() // A method call is an expression
new Object() // Creation of an object is an expression
new int[] // Creation of an object is an expression
In general, an expression consists of the following forms:
someIdentifier
MyClass.someField
1
, 1.0
, 'X'
, "hello"
, false
and null
MyClass.class
this
and <TypeName> . this
( a + b )
new MyClass(1, 2, 3)
new int[3]
obj.someField
or this.someField
vector[21]
obj.doIt(1, 2, 3)
MyClass::doIt
!a
or i++
a + b
or obj == null
(obj == null) ? 1 : obj.getCount()
obj -> obj.getCount()
The details of the different forms of expressions may be found in other Topics.
In most cases, an expression has a static type that can be determined at compile time by examining and its subexpressions. These are referred to as stand-alone expressions.
However, (in Java 8 and later) the following kinds of expressions may be poly expressions:
When an expression is a poly expression, its type may be influenced by the expression's target type; i.e. what it is being used for.
The value of an expression is assignment compatible with its type. The exception to this is when heap pollution has occurred; e.g. because "unsafe conversion" warnings have been (inappropriately) suppressed or ignored.
Unlike many other languages, Java does not generally allow expressions to be used as statements. For example:
public void compute(int i, int j) {
i + j; // ERROR
}
Since the result of evaluating an expression like cannot be use, and since it cannot affect the execution of the program in any other way, the Java designers took the position that such usage is either a mistake, or misguided.
However, this does not apply to all expressions. A subset of expressions are (in fact) legal as statements. The set comprises:
void
or non-void
).