File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Type casting null object reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Type casting null object reference" Watch "Type casting null object reference" New topic
Author

Type casting null object reference

May Pat
Ranch Hand

Joined: Jul 01, 2002
Posts: 32
Question 9 from www.jiris.com Exam 1 asks:
What is the output of trying to compile and run the following?

1: public class Test009 extends T
2: {
3: public static void main(String args[])
4: {
5: Test009 t = null;
6: T tt = (T)t;
7: System.out.print(t);
8: System.out.print(" ");
9: System.out.println(tt);
10: }
11: }
12:
13: class T{}
The answer is code compiles and run with output: null null.
My question is why it is legitimate to type cast a null object reference (line 6) since there's no object exists?
Thank you very much


May P.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
null is a legal value of any reference type.


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
In fact there is a widdening reference conversion from null to any class, array or interface. (JLS 5.1.4)


SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Type casting null object reference
 
Similar Threads
ExamCram
When is a class loaded?
Is it NullPointerException??
Jiris, Mock 1, Q9
null printing