Java Reference
In-Depth Information
would be stored in
str
. However, the address of the allocated memory space will be
different from that in the first statement. To be specific, suppose that the address of the
allocated memory space is
3850
. Figure 3-4 illustrates the result.
3850
3
str
3850
Hello there!
FIGURE 3-4
Variable
str
, its value, and the object
str
This is an important property of reference variables of the
String
type and
String
objects, and must be recognized and understood. Furthermore, it is especially important
to understand this property when we start comparing strings.
To simplify Figure 3-4, we usually use the format shown in Figure 3-5.
str
Hello there!
FIGURE 3-5
Variable
str
and the object
str
In Figure 3-5, the arrow originating in the box
str
means that
str
contains an address.
The arrow pointing to the memory space containing the value
"Hello there!"
means
that the variable
str
contains the address of the object containing the value
"Hellothere!"
.
We will use this arrow notation to help explain various examples.
You might ask: What happened to memory space
2500
and the string
"Java Programming"
stored in it? If no other
String
variable refers to it, then sometime during program
execution, the Java system reclaims this memory space for later use. This is called
garbage collection.
If you do not want to depend on the system to choose when to perform garbage collection,
then you can include the statement:
System.gc();
in your program to instruct the computer to run the garbage collector (immediately). In
general, it is not necessary to do so.
We can now summarize the discussion of the preceding sections. You can declare two types
of variables in Java: primitive type variables and reference variables, as shown in Figure 3-6.
Search WWH ::
Custom Search