Java Reference
In-Depth Information
9.26
What is the output of the following programs?
import
java.util.Date;
import
java.util.Date;
public class
Test {
public static void
main(String[] args) {
Date date =
null
;
m1(date);
System.out.println(date);
}
public class
Test {
public static void
main(String[] args) {
Date date =
new
Date(
1234567
);
m1(date);
System.out.println(date.getTime());
}
public static void
m1(Date date) {
date =
new
Date();
}
}
public static void
m1(Date date) {
date =
new
Date(
7654321
);
}
}
(a)
(b)
import
java.util.Date;
import
java.util.Date;
public class
Test {
public static void
main(String[] args) {
Date date =
new
Date(
1234567
);
m1(date);
System.out.println(date.getTime());
}
public class
Test {
public static void
main(String[] args) {
Date date =
new
Date(
1234567
);
m1(date);
System.out.println(date.getTime());
}
public static void
m1(Date date) {
date.setTime(
7654321
);
}
}
public static void
m1(Date date) {
date =
null
;
}
}
(c)
(d)
An array can hold objects as well as primitive type values.
Key
Point
ChapterĀ 7, Single-Dimensional Arrays, described how to create arrays of primitive type ele-
ments. You can also create arrays of objects. For example, the following statement declares
and creates an array of ten
Circle
objects:
Circle[] circleArray =
new
Circle[
10
];
To initialize
circleArray
, you can use a
for
loop like this one:
for
(
int
i =
0
; i < circleArray.length; i++) {
circleArray[i] =
new
Circle();
}
An array of objects is actually an
array of reference variables
. So, invoking
circleArray[1].
getArea()
involves two levels of referencing, as shown in FigureĀ 9.19.
circleArray
references the entire array;
circleArray[1]
references a
Circle
object.
Note
When an array of objects is created using the
new
operator, each element in the array is
a reference variable with a default value of
null
.
Search WWH ::
Custom Search