Java Reference
In-Depth Information
2500
str
2500
Java Programming
FIGURE 3-2
Variable
str
and the data it points to
3
For the
String
variable
str
, the statement in Line 4 causes the system to allocate memory
space starting at, say, location
2500
, stores the string (literal)
"Java Programming"
in this
memory space, and then stores the address
2500
in the memory space of
str
.
The next obvious question is: How does this happen? In reality, for the most part, the effect
of the statement in Line 4 is the same as the effect of the following statement:
str =
new
String("Java Programming");
//Line 5
In Java,
new
is an operator. It causes the system to allocate memory space of a specific
type, store specific data in that memory space, and return the address of the memory
space. Therefore, the statement in Line 4 causes the system to allocate memory space
large enough to store the string (literal)
"Java Programming"
, stores this string in that
memory space, and returns the address of the allocated memory space. The assignment
operator stores the address of that memory space into the variable
str
.
As noted, for the most part the effects of the statements in Lines 4 and 5 are the same.
In both the cases, the
String
variable
str
will point to a memory location that contains
the string
"Java Programming"
. Note that in the statement in Line 5, the operator
new
is used explicitly, while the statement in Line 4 does not explicitly use the operator
new
. In reality, when the statement in Line 4 executes, it first looks if the program
has already created the string
"Java Programming"
. If this is the case, then the
String
variable
str
will point to that memory location. However, when the statement
in Line 5 executes, the system will allocate a memory space, store the string
"Java
Programming"
into that memory space, and then store the address of that memory
space into
str
. This is a key difference and plays an important role when strings and
String
variables are compared, which we will explain in Chapter 4.
String
is not a primitive data type. In Java terminology, the data type
String
is defined
by the
class
String
. In this and subsequent chapters, you will encounter some other
classes provided by the Java system. In Chapter 8, you will learn how to create your own
classes.
In Java, variables such as
str
are called reference variables. More formally, reference
variables are variables that store the address of a memory space. In Java, any variable
declared using a
class
(such as the variable
str
) is a reference variable. Because
str
is a
reference variable declared using the
class
String
, we say that
str
is a reference
variable of the
String
type.
Search WWH ::
Custom Search