aspose 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 OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Type casting null object reference" Watch "Type casting null object reference" New topic

Type casting null object reference

May Pat
Ranch Hand

Joined: Jul 01, 2002
Posts: 32
Question 9 from 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: }
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
It is sorta covered in the JavaRanch Style Guide.
subject: Type casting null object reference