Expression Basics

suggest change

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`

The details of the different forms of expressions may be found in other Topics.

The Type of an Expression

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

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.

Expression Statements

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:

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents