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:
- Simple identifiers; e.g. `someIdentifier`
- Qualified identifiers; e.g. `MyClass.someField`
- Literals; e.g. `1`, `1.0`, `'X'`, `"hello"`, `false` and `null`
- Class literal expressions; e.g. `MyClass.class`
- `this` and `<TypeName> . this`
- Parenthesized expressions; e.g. `( a + b )`
- Class instance creation expressions; e.g. `new MyClass(1, 2, 3)`
- Array instance creation expressions; e.g. `new int[3]`
- Field access expressions; e.g. `obj.someField` or `this.someField`
- Array access expressions; e.g. `vector[21]`
- Method invocations; e.g. `obj.doIt(1, 2, 3)`
- Method references (Java 8 and later); e.g. `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: