• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof operator and instanceOf() Method

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In which class is the instanceOf() method you're talking about? I searched the JDK documentation and didn't find any instanceOf() method.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jesper and Rob..
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic