This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes instanceOf - most useless operator ever? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceOf - most useless operator ever?" Watch "instanceOf - most useless operator ever?" New topic
Author

instanceOf - most useless operator ever?

Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

So I thought I had found an errata in a most excellent SCJP book. But when I actually typed in the code, of course the author was correct.



The last line will produce the compiler error:


So the only comparisons that get by the compiler are Object or Component or Ticker.

I thought this would be a run-time thing, and that "no 't' is not a String" would produce boolean false.

So if the only objects that I can use on either side of the operator are *already* in the same tree, I already know that they are in an "IS-A" relation (assuming that the LHS operand is lower in the tree than the RHS).

So what good is instanceOf ?
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1746
    
    2
Originally posted by Mike Curwen:
So if the only objects that I can use on either side of the operator are *already* in the same tree, I already know that they are in an "IS-A" relation (assuming that the LHS operand is lower in the tree than the RHS).

I don't have any good response to your question in general, but just wanted to point out that what you're saying is not exactly true if the type you're checking against is an interface.
Checking instanceof Iterator below compiles and evaluates to false.
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1746
    
    2
Ok, I think I'm getting it.
If you upcast your refrence all the way to Object, then the compiler's OK with instanceof String:
Object t7 = new Ticker() ;
boolean test7 = t7 instanceof String ;
System.out.println( test7 );
But if your reference is Ticker (or Component or Marker or SubMarker...), then it knows even at compile time that the check of instanceof is false/not relevant:
Component t8 = new Ticker();
boolean test8 = t8 instanceof String ;
System.out.println( test8 );
=> compiler error
[ February 05, 2003: Message edited by: Michael Matola ]
 
jQuery in Action, 2nd edition
 
subject: instanceOf - most useless operator ever?
 
Similar Threads
instanceof Problem
instanceof question
Question from Ch 3 Self Test, Sierra/Bates Book
Kathy/Bert book ch 3 self test q 2
instanceof example not compiling