Java Language Reference

Previous Chapter 4

4.15 Data Type of an Expression

If an expression produces a value, that value is of some particular data type. In some cases, it is possible to determine the exact type that is produced by an expression, based on the types of the literals, variables, and methods that an expression references. For those expressions that produce object references, it is typically only possible to determine the type of the referenced object when the expression is evaluated at runtime.

The types of many expressions are ambiguous because of the way Java data types are defined. There is no ambiguity for variables, array elements, and method return values of primitive types, however. These expressions always produce the exact types specified in their declarations.

There can be ambiguity when a variable, array element, or method return value is declared to have a class or interface reference type. The ambiguity exists because a class reference may actually refer to an object of the intended class or a subclass of that class. For example, consider a variable that is declared to contain a reference to a Number object:

double square(Number n){
    return n.doubleValue()*n.doubleValue();

When the Java compiler sees the variable n used in an expression, it knows that the object that is referenced could be an Integer, Long, Float, or Double object because the java.lang package defines those subclasses of Number. It is also possible, however, that the variable refers to some other subclass of Number defined elsewhere. All that the compiler can be certain of is that at runtime n will refer to an object of a subclass of Number. The variable n cannot refer to a Number object because Number is an abstract class, so there are no Number objects.

The one exception to the ambiguity of class-type object references occurs when the class used to declare a variable, array element, or method return type is a final class. If a class is declared to be final, it cannot be subclassed, so there is no ambiguity.

Ambiguity also exists if the type of a reference is an interface type, since the reference can refer to an object of any class that implements the interface. The actual class is not usually known until runtime.

The fact that the type of value produced by an object reference expression cannot be determined until it is evaluated at runtime can affect the evaluation of other expressions in the following ways:

References Array Types; Assignment Operators; Casts; Class Types; Interface Types; Method Call Expression; The instanceof Operator; The throw Statement

Previous Home Next
Order of Operations Book Index Constant Expressions

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java