Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null & instanceof

 
Akash Singhal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



Returns false

However
prints null.

Besides null also gets typecast into any user-defined objects inspite of
instanceof returning false.. how is it possible???Thanking in advance

Regards,
 
Abhinay Verma
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
null can be cast to any reference type without any side-effects. However, null is never an instance of any class. Therefore,
null instanceof Object will return false
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "<reference> instanceof <class>" operator works on the actual instance referred to by <reference>. Since a null reference has no class, it cannot be an instace of any class, and it always returns false.

[ Disabled smilies. ]
[ February 21, 2005: Message edited by: David Harkness ]
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(String(null));

This will give compile time error . What you want to do ?
 
Akash Singhal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No Rathi,
System.out.println(String(null)) prints null onto the screen.
System.out.println(null) gives compile time error.Please check..

Regards
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rathi is correct.

System.out.println(String(null))

Compile-time error.


System.out.println(null)

Prints literal "null"

Please check.
[ February 21, 2005: Message edited by: Tony Morris ]
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Akash Singhal:
System.out.println(String(null)) prints null onto the screen.
This is definitely a compile-time error. Do you want to cast the null reference to a String type?
 
Paulo Aquino
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

prints the string null

compile time error
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic