Only atomic pieces of expressions (e.g., the literal true) have a type. Composite expressions don’t have a type.


Expressions that consist of multiple parts have no type


Expressions that consist of multiple parts have a type

Here is what's right.

The type of a composite expression is determined by the operator’s (or method’s) result type.

For example, the expression 1+2 has type int (because the + operator on two int operands produces an int result), and the expression Math.sin(2.5) has type double, because method Math.sin(double) has the return type double.

How can you build on this misconception?

This misconception provides an interesting starting point for discussions on the structure of expressions (e.g., that even a single literal is an expression), on static typing, and on how exactly the type of an expression is determined at compile time.

Determining the Type of an Expressions

Many expressions in Java are so-called standalone expressions: their type can be determined entirely based on their source code.

However, some language features (like lambdas) lead to some expressions not being standalone expressions. Those expressions are so-called poly expressions, and their type has to be determined also from their context (the source code surrounding the expression).

An example of a standalone expression is x * 2: its type can be determined without looking at its surrounding code (except for looking at the declaration of variable x to find the type of x). Assume the type of variable x is int. The expression will have the same type no matter whether it is placed in long l = ___ or in Math.sin(___) or in float f = ___.

An example of a poly expression is x -> x: its type cannot be determined without looking at its surrounding code. For example, the type could be Function<Double,Double> if placed in Function<Double,Double> f = ___, or it could be Function<Pair,Pair> if placed in (Function<Pair,Pair>)___.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.