This week's giveaways are in the MongoDB and Jobs Discussion forums. We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line! See this thread and this one for details.
If an instanceof comparison returns false then a similar cast will throw a ClassCastException. For example: Object obj = new java.awt.Button(); boolean b = obj instance of String; //b is equal to false String s = (String)obj; // throws ClassCastException There is one and only one exception to this rule. What is it?
Originally posted by Thomas Paul: If an instanceof comparison returns false then a similar cast will throw a ClassCastException. For example: Object obj = new java.awt.Button(); boolean b = obj instance of String; //b is equal to false String s = (String)obj; // throws ClassCastException There is one and only one exception to this rule. What is it?
null ? Because it can be cast into anything?
Ernest Friedman-Hill
author and iconoclast
Marshal
Hey Thomas I like you questions a lot. I think they are helping many Ranchers.
SCJP2. Please Indent your code using UBB Code
Jui Mahajan
Ranch Hand
Joined: Jun 02, 2003
Posts: 62
posted
0
how come null can be cast to anything ? I thought thatusing instanceof operator on a null would always return false ? Therefore, null cannot be cast to any object. ALso, I had thought that equals() method returns false on null; i.e. anyobject.equals (null) is always false . AM i right...pls clarify.
-----jui<br />scjp1.4
Jose Botella
Ranch Hand
Joined: Jul 03, 2001
Posts: 2120
posted
0
According to JLS 5.1.4 Widening reference conversions there ia a widening reference conversion "From the null type to any class type, interface type, or array type." Also from JLS 5.5 "The cast can be determined to be correct at compile time. A cast from the compile-time type S to compile-time type T is correct at compile time if and only if S can be converted to T by assignment conversion (�5.2). " And finally from JLS 5.2 "Assignment contexts allow the use of an identity conversion (�5.1.1), a widening primitive conversion (�5.1.2), or a widening reference conversion (�5.1.4). " hope it helps [ August 10, 2003: Message edited by: Jose Botella ]
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Since a null object always casts cleanly, that is the one exception to the rule about instanceof and ClassCastException. Object obj = null; boolean b = obj instance of String; //b is equal to false String s = (String)obj; // executes without Exception