Programming and Problem Solving with Java

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

assigns the string “The square of 12 is 144”to the variable result. Java converts the integer
literal 144 into the string “ 144 ”before performing the concatenation.


Initializer Expressions Now that we have defined expressions, we can generalize the field dec-


laration syntax to allow for the use of an expression in initializing the field.


The following declarations are, therefore, legal:


finalString WORD1 = “Introduction”;
finalString WORD3 = “Java “+ WORD1;
finalString WORD5 = “Design “+ WORD3;


They store “Design Java Introduction”as the value of the constantWORD5.


Modifiers Type-Name Identifier = Expression

Field-Declaration

, Identifier = Expression ;

Assignment of Primitive Types Versus Objects


After reading the preceding discussion of assignment statements and expressions, you may
wonder what really happens inside the computer when assignment occurs. For Java’s primitive
types that represent simple data values such as characters and numbers, the answer is
straightforward: The value on the right side of the equals sign is stored in the memory location
corresponding to the identifier on the left-hand side.
But what about objects such as strings? Surely they can’t fit into a single memory location?
The answer is no, they can’t. So how does assignment work in that case?
Assignment of objects is done indirectly. A variable of the object data type contains a value
that is the memory address where the actual object is stored. When Java needs to operate on an
object, it uses the value stored in the variable to find the object in memory. This process takes
place automatically, so we don’t have to worry about it. With respect to assignment, however, it
means that assigning one object variable to another works just the same as assigning one inte-
ger variable to another. The value contained in one variable is copied from its memory location
into the location associated with the other variable. For an object, this value is an address in
memory.
In later chapters we will return to this topic and note that it has some additional
consequences. In the meantime, we will avoid situations where this issue might cause
problems.
Free download pdf