aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes null instanceof  an Object ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "null instanceof  an Object ?" Watch "null instanceof  an Object ?" New topic
Author

null instanceof an Object ?

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14347
    
  22

null instanceof <anything> always returns false.

jose chiramal wrote:am able to return null here, the compiler doesnt complain. However when i do instanceOf Object it doesnt enter the if loop. How is this possible ?

What do you mean? There is no loop in the code you posted above. (An if-statement does not make a loop!).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
I've never tried it, but your if condition looks like you are saying if null is an instance of String. Will that ever return true? And can you clarify your question a little? Are you confused as to why it is returning null when you aren't entering your if condition?


SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
What I meant was this :

The method is expecting a return type of Object , and am returning a null value and this compiles successfully. How is this poossible ?

Which violates the below ?

  • null instanceof <anything> always returns false.
  • Ankit Garg
    Sheriff

    Joined: Aug 03, 2008
    Posts: 9313
        
      17

    You can assign a null value to any reference variable. But the null value is not an instanceof Object or any other class. When you assign a reference variable null, it means that the reference variable doesn't refer to any object.

    Also this has been asked to you earlier by Christophe and I'm saying it again, try to ask the problem outside of the code. Instead of your question in the code itself, you can give the line that you are confused in a number and ask the question relative to that line number. Eg.

    At line (2) I am able to return null here, the compiler doesnt complain. However when i do instanceOf Object at line (1) it doesnt enter the if loop. How is this possible ?


    SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: null instanceof an Object ?