Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.1 The Elements of Java Programs | 55

(^1) Many early programming languages, some of which are still in use today, allow a value of any type to
be stored in a variable. This weak typing was inherited from assembly language programming and has
been a source of many programming errors. Modern languages check that variables contain proper val-
ues, thereby helping us to avoid such errors.
called a variable, and its contents are the variable value. The symbolic name that
we associate with a memory location is the variable nameor variable identifier.In
practice, we often refer to the variable name more briefly as the variable.
Declaring a variablemeans specifying both its name and its data type or class.
This specification tells the compiler to associate a name with a memory location
and informs it that the values to be stored in that location are of a specific type
or class (for example,charor String). The following statement declares myCharto
be a variable of type char:
charmyChar;
Notice that the declaration does not specify what value is stored in myChar. Rather,
it specifies that the name myCharcan hold
a value of type char. At this point,myChar
has been reserved as a place in memory
but it contains no data. Soon, we will see
how to actually put a value into a variable.
(See Figure 2.1.)
Java is a strongly typedlanguage, which
means that a variable can contain a value
only of the type or class specified in its
declaration.^1 Because of the above decla-
ration, the variable myCharcan contain only
a charvalue. If the Java compiler comes
across an instruction that tries to store a
value of the wrong type, it gives an error
message, usually something like “Cannot
assign String to char.”
Here’s the syntax template for a variable declaration:
Modifiers Type-Name Identifier , Identifier... ;
Variable-Declaration
Variable A location in mem-
ory, referenced by an identifier,
that contains a data value that
can be changed
Strongly typed A property of
a programming language in
which the language allows vari-
ables to contain only values of
the specified type or class
Variable Identifier
memory location 1101010011
myChar
Variab?
Figure 2.1 Variable

Free download pdf