• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

When will instanceof return false

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
instanceof ofcourse returns false when null is used... like null instance of Integer returns false.

Barring that , what are the cases when it returns false..because instanceof gives a compiler error when used between incompatible types.
And when invoked between an object and class belonging to same hierarchy it always returns true.

pls explain.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class BBB { }
class CCC extends BBB { }
The instanceof operator is useful when it is necessary to find the
runtime type of an object. The declared type might be a supertype.

class DDD extends BBB { }
public class X {
public static void main(String[] args) {
BBB c = new CCC();
BBB d = new DDD();
X.checkIt(c); // prints true
X.checkIt(d); // prints false
}
private static void checkIt(BBB b) {
System.out.println(b instanceof CCC);
}
}
 
Vepa Sritej
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Allan..
 
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also you can use "instanceof" operator with interfaces:

reference instanceof InterfaceX

Using instanceof with Interfaces as a second parameter never leads to compile time error. It checks if the reference's Class or up in the hierarchy implements the Inteface.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when you assign sub class to super class instance then instanceof true or else returns false.If Honda extends Car
if say
car[] c1=new Honda(); that is works fine
 
this is supposed to be a surprise, but it smells like a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic