10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

TYPES, VALUES, AND VARIABLES Variables of Reference Type 4.12.2<br />

4.12 Variables<br />

A variable is a storage location and has an associated type, sometimes called its<br />

compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3).<br />

A variable’s value is changed by an assignment (§15.26) or by a prefix or postfix<br />

++ (increment) or -- (decrement) operator (§15.14.2, §15.14.3, §15.15.1,<br />

§15.15.2).<br />

Compatibility of the value of a variable with its type is guaranteed by the<br />

design of the <strong>Java</strong> programming language, as long as a program does not give rise<br />

to unchecked warnings (§4.12.2.1). Default values are compatible (§4.12.5) and<br />

all assignments to a variable are checked for assignment compatibility (§5.2), usually<br />

at compile time, but, in a single case involving arrays, a run-time check is<br />

made (§10.10).<br />

4.12.1 Variables of Primitive Type<br />

A variable of a primitive type always holds a value of that exact primitive type.<br />

4.12.2 Variables of Reference Type<br />

A variable of a class type T can hold a null reference or a reference to an instance<br />

of class T or of any class that is a subclass of T. A variable of an interface type can<br />

hold a null reference or a reference to any instance of any class that implements<br />

the interface.<br />

DISCUSSION<br />

DRAFT<br />

Note that a variable is not guaranteed to always refer to a subtype of its declared type, but<br />

only to subclasses or subinterfaces of the declared type. This is due to the possibility of<br />

heap pollution discussed below.<br />

If T is a primitive type, then a variable of type “array of T ” can hold a null reference<br />

or a reference to any array of type “array of T ”; if T is a reference type,<br />

then a variable of type “array of T ” can hold a null reference or a reference to any<br />

array of type “array of S” such that type S is a subclass or subinterface of type T.<br />

In addition, a variable of type Object[] can hold an array of any reference type.<br />

67

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!