Given a user-defined data type such as Dog, we would like to create an instance of Dog and use it subsequently in a program. Doing so requires both variable definition and assignment operations. A data definition operation specifies a data type and a variable name, and optionally, an initial value:
| Data Definition |
| <data-type> <variable>; |
| <data-type> <variable-1>, <variable-2>, ..., <variable-n>; |
| <data-type> <variable> = <data-value>; |
The data type may be a primitive, or built-in, type or a user-defined type such as Dog. The value may be a literal value or an instance of a user-defined type such as Dog. Primitive data types are discussed in Data types.
Several examples of data definitions follow:
| Data Definition Examples |
| int x; |
| int x = 9; |
| boolean terminate = false; |
| Dog dog = new Dog(); |
The new operator is described in the next panel (Creating class instances).
An assignment operation can occur in the following contexts:
| Assignment Operation |
| <data-type> <variable> = <data-value>; |
<data-type> <variable>; <other-statements>... <variable> = <data-value>; |
The data value to the right of the assignment operator can be a literal value, or any operation that produces a scalar value. Several examples follow:
| Assignment Example | Comment |
| int x = 4; | Data definition with assignment |
| x = 9; | Assumes prior definition of x |
| temperature = 21.4; | Assumes prior definition of temperature |
| dog = new Dog(); | Assumes prior definition of dog |
copyright 1996-2000 Magelang Institute dba jGuru