Java Reference
In-Depth Information
An object variable can also be set to
null
, which is a reserved word in Java.
A null reference specifically indicates that a variable does not refer to an object.
Note that, although we've declared a
String
reference variable, no
String
object actually exists yet. The act of creating an object using the
new
operator is
called
instantiation
. An object is said to be an
instance
of a particular class. To
instantiate an object, we can use the
new
operator, which returns the address of
the new object. The following two assignment statements give values to the two
variables declared above:
num = 42;
name =
new
String("James Gosling");
constructor
is invoked
to help set it up initially. A constructor is a special method that has the
same name as the class. In this example, the parameter to the construc-
tor is a string literal that specifies the characters that the string object
will hold. After these assignments are executed, the variables can be
depicted as:
After the
new
operator creates the object, a
KEY CONCEPT
The
new
operator returns a reference
to a newly created object.
num
42
name
"James Gosling"
Since an object reference variable holds the address of the object, it can be
thought of as a
pointer
to the location in memory where the object is held. We
could show the numeric address, but the actual address value is irrelevant—
what's important is that the variable refers to a particular object.
After an object has been instantiated, we use the
dot operator
to access its
methods. We've used the dot operator many times already, such as in calls to
System.out.println
. The dot operator is appended directly after the object refer-
ence, followed by the method being invoked. For example, to invoke the
length
method defined in the
String
class, we can use the dot operator on the
name
reference variable:
VideoNote
Creating objects.
count = name.length()
The
length
method does not take any parameters, but the parentheses are still
necessary to indicate that a method is being invoked. Some methods produce a value
that is
returned
when the method completes. The purpose of the
length
method of
the
String
class is to determine and return the length of the string (the number of
characters it contains). In this example, the returned value is assigned to the vari-
able
count
. For the string
"James Gosling"
, the
length
method returns
13
, which
Search WWH ::
Custom Search