wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes instanceof operator and instanceOf() Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof operator and instanceOf() Method" Watch "instanceof operator and instanceOf() Method" New topic
Author

instanceof operator and instanceOf() Method

Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 627
Hi,

What is the difference between these two? if someone can explain with a code example it would be great.

Thanks.
[ September 16, 2008: Message edited by: Arjun Reddy ]

Be Humble... Be Nice.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

In which class is the instanceOf() method you're talking about? I searched the JDK documentation and didn't find any instanceOf() method.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19680
    
  19

I think Arjun means Class.isInstance().

The difference is that with instanceof, the class has to be hardcoded. It is String.class, Date.class, or something similarly hardcoded.

With Class.isInstance(), you can get the Class object from anywhere. It can be hardcoded as well (String.class), but you can even get it dynamically:

It also allows you to use one single method for multiple classes. An example, to filter out elements from a collection that are not of a specific class:

You can now call this method with String.class, Date.class, Map.class (yes, also with interfaces) or Class.forName("mypackage.MyClass") - it doesn't matter.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 627
It says here in the http://faq.javaranch.com/java/ScjpFaq under
What are some potential trips/traps in the SCJP exam?

Thanks.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19680
    
  19

Ah right.

In that case, there is no such method as instanceOf(). instanceof, all lowercase, is an operator and the other one is made up.
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 627
Thanks Jesper and Rob..
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

Originally posted by Arjun Reddy:
It says here in the http://faq.javaranch.com/java/ScjpFaq under
What are some potential trips/traps in the SCJP exam?


The FAQ says the following:
instanceOf is not the same as instanceof.

It doesn't say anything about an instanceOf() method. It just says that instanceof is written with a lower-case o, and not with a capital O.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof operator and instanceOf() Method