• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Type casting null object reference

 
May Pat
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
null is a legal value of any reference type.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact there is a widdening reference conversion from null to any class, array or interface. (JLS 5.1.4)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic