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 an Object ?

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!).
 
W. Joe Smith
Ranch Hand
Posts: 710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Posts: 9528
    32
    Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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 ?
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic