Java Reference
In-Depth Information
primitive variables. As shown in Figure 8.9, the assignment statement
c1 = c2
copies the
reference of
c2
into
c1
for reference variables. After the assignment, variables
c1
and
c2
refer to the same object.
Object type assignment
c1 = c2
Before:
After:
c1
c1
c2
c2
c2: Circle
c1: Circle
c2: Circle
c1: Circle
radius = 9
radius = 5
radius = 9
radius = 5
F
IGURE
8.9
Reference variable
c2
is copied to variable
c1
.
Note
As illustrated in Figure 8.9, after the assignment statement
c1 = c2
,
c1
points to the
same object referenced by
c2
. The object previously referenced by
c1
is no longer use-
ful and therefore is now known as
garbage
. Garbage occupies memory space, so the Java
runtime system detects garbage and automatically reclaims the space it occupies. This
process is called
garbage collection
.
garbage
garbage collection
Tip
If you know that an object is no longer needed, you can explicitly assign
null
to a ref-
erence variable for the object. The JVM will automatically collect the space if the object
is not referenced by any reference variable.
8.7
Which operator is used to access a data field or invoke a method from an object?
✓
✓
Check
8.8
Point
What is an anonymous object?
8.9
What is
NullPointerException
?
8.10
Is an array an object or a primitive type value? Can an array contain elements of an
object type as well as a primitive type? Describe the default value for the elements of
an array.
8.11
What is wrong with each of the following programs?
1
public class
ShowErrors {
2
public static void
main(String[] args) {
3 ShowErrors t =
new
ShowErrors(
5
);
4 }
5 }
1
public class
ShowErrors {
2
public static void
main(String[] args) {
3 ShowErrors t =
new
ShowErrors();
4 t.x();
5 }
6 }
(a)
(b)