Java Reference
In-Depth Information
for primitive variables. As shown in Figure 9.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
9.9
Reference variable
c2
is copied to variable
c1
.
Note
As illustrated in Figure 9.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 useful
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 refer-
ence variable for the object. The JVM will automatically collect the space if the object is
not referenced by any reference variable.
9.7
✓
✓
Which operator is used to access a data field or invoke a method from an object?
Check
9.8
What is an anonymous object?
Point
9.9
What is
NullPointerException
?
9.10
Is an array an object or a primitive type value? Can an array contain elements of an
object type? Describe the default value for the elements of an array.
9.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)
1
public class
ShowErrors {
2
public void
method1() {
3 Circle c;
4 System.out.println(
"What is radius "
5 + c.getRadius());
6 c =
new
Circle();
7 }
8 }
1
public class
ShowErrors {
2
public static void
main(String[] args) {
3 C c =
new
C(
5.0
);
4 System.out.println(c.value);
5 }
6 }
7
8
class
C {
9
int
value =
2
;
10 }
(c)
(d)
Search WWH ::
Custom Search