Java Reference
In-Depth Information
The memory space 2500 , where the string (literal) "Java Programming" is stored, is
called a String object. We call String objects instances of the class String .
Because str is a reference variable of the String type, str can store the address of any
String object. In other words, str can point to or refer to any String object. More-
over, it follows that we are dealing with two different things—the reference variable str
and the String object that str points to. We call the String object that str points to,
which is at memory space 2500 in Figure 3-2, the object str .
To emphasize that the String object at memory space 2500 is the object str , we can
redraw Figure 3-2 as Figure 3-3.
Object
str
reference variable
2500
str
2500
Java Programming
FIGURE 3-3 Variable str and object str
Using the operator new to create a class object is called instantiating an object of
that class .
Let us summarize the Java terminology used in the preceding paragraphs, especially the use of
the terms variable and object. While working with classes, we declare a reference variable of a
class type and then, typically, we use the operator new to instantiate an object of that
class type and store the address of the object into the reference variable. For example,
suppose that refVar is a reference variable of a class type. When we use the term variable
refVar , we mean the value of refVar , that is, the address stored in refVar .Whenweuse
the term object refVar , we mean the object whose address is stored in refVar .Theobject
that refVar points to can be accessed via the variable refVar .
The next question is: How can you change the value of the object from "JavaProgramming" ,
as shown in Figure 3-3, to "Hello there!" ? To do so, you must look at the class String
and see if it provides a method that allows you to change the value of the (existing) object
from "Java Programming" to "Hello there!" . (The next section briefly describes
what a method is.) Unfortunately, the class String does not provide any such method.
(The class String is discussed in some detail later in this chapter.) In other words, the
value of the String object at memory space 2500 cannot be altered. It thus follows that
String objects are immutable; that is, once they are created, they cannot be changed.
You could execute another statement, similar to the statement in Line 4, with the value
"Hello there!" . Suppose that the following statement is executed:
str = "Hello there!";
This statement would again cause the system to allocate memory space to store the string
"Hello there!" , if no such string already exists, and the address of that memory space
Search WWH ::




Custom Search