Java Reference
In-Depth Information
Let's take a look at an example. See if you can determine the output of the following
statements:
3. String s = “Hello, World”;
4. if(s instanceof String) {
5. System.out.print(“one”);
6. }
7. if(s instanceof Object) {
8. System.out.print(“two”);
9. }
10. if(s instanceof java.io.Serializable) {
11. System.out.print(“three”);
12. }
The reference
s
points to a
String
object, so line 4 is
true
and
“one”
is printed on line 5.
Every object in Java is of type
Object
, so line 7 is
true
for any reference; therefore,
“two”
is printed. The
String
class implements the
Serializable
interface, which makes
String
objects
Serializable
objects as well. Therefore, line 10 is also
true
and the output of the
previous code is
onetwothree
One of the main usages of the
instanceof
operator is when you cast a reference to a
subclass type. If you cast a reference to an invalid data type, a
ClassCastException
is
thrown by the JVM. For example, the following statements compile, but at runtime an
exception is thrown:
Object x = new String(“a String object”);
Date d = (Date) x;
The output of this code is
Exception in thread “main” java.lang.ClassCastException:
java.lang.String cannot be cast to java.util.Date
Using the
instanceof
operator, you can avoid this situation:
17. Object x = new String(“a String object”);
18. if(x instanceof Date) {
19. Date d = (Date) x;
20. }
Because
x
points to a
String
object and not a
Date
object, line 18 is
false
and the
invalid cast does not occur, avoiding the uncaught
ClassCastException
. We will see the
instanceof
operator again in Chapter 6.
Search WWH ::
Custom Search