313

What is the 'instanceof' operator used for?

I learned that Java has the instanceof operator. Can you elaborate where it is used and what are its advantages?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Nikunj Patel
  • 21,853
  • 23
  • 89
  • 133
  • 4
    Have you had a look at [this?](http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm) –  Sep 23 '11 at 09:24
  • 2
    This SO link should give you a lot of idea: http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom – Scorpion Sep 23 '11 at 09:28
  • 4
    If I google your question I get 11.7 million results. Is there something you would like to know which has not already been discussed at length? – Peter Lawrey Sep 23 '11 at 09:51
  • 31
    Dup maybe, but questions like this make SO a great resource across all skill levels. I am glad this was the top result when I goog'd. – Edward Newell Feb 07 '14 at 01:57
  • Here's a good article on the use of this: https://www.javatpoint.com/downcasting-with-instanceof-operator – Jason Aug 10 '17 at 13:25
  • Not saying this is not a good question. But, I am very amazed how such highly discussed-all-over-the-web questions got so many upvotes and I'm pretty sure if someone asks such a question today, they will get lots of downvotes right away. So, I'd be glad if someone give some elaboration in case there is any difference. – Mehdi Haghgoo Jan 23 '18 at 06:00

4 Answers4

395

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

Example:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • 2
    Is the `Integer.class` format actually legal? When I attempt to use it in your example, in Eclipse, I get `Syntax error on token "class", Identifier expected`. However, switching it to simply `Integer` works fine. – etech May 22 '13 at 15:00
  • @etech you're right, I'll fix that. It's been a while since I wrote that answer ;) – Thomas May 23 '13 at 16:14
  • 2
    A common place to find this method is in `.equals()` methods. it's common for intelliJ to generate equals methods that use `instanceof` – Sam Jun 15 '15 at 13:22
  • Just want to add why usage of this operator indicates design flaws. The abstraction that needs to be cast to the concrete type doesn't provide enough information. It's either just some bad abstraction or abstraction that is used in a wrong domain. You can check detailed explanation with an example here: https://medium.com/@aerokhin/instanceof-should-be-your-last-resort-4b8b3667cd17 . – Aleksandr Erokhin Sep 14 '19 at 08:38
73

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37
Jayendra
  • 52,349
  • 4
  • 80
  • 90
51

instanceof can be used to determine the actual type of an object:

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 1
    There are definitely cases when you should use instanceof in your design, especially with developing an API and throwing misuse exceptions – Jace J McPherson Jun 15 '16 at 19:02
  • 2
    Loved the answer, but I'm creating a lexer and I need to use `instanceof` to determine the type of tokens (e.g. `Identifier`, `Literal`, etc..., extending from `Token`). If I was not going to use `instanceof`, then I'd have an unique `Token` class and would have to create various unnecessary different type of fields to hold the value of the actual token. –  Jul 18 '17 at 14:29
  • miss-leading answer, which taking one situation and making judge on whole keyword =\ – Reishin Jan 23 '18 at 05:07
  • @Hydro You could also introduce a dedicated \texttt{enum} class for your kinds of tokens. – Marc van Dongen Apr 12 '18 at 06:29
29

instanceof is a keyword that can be used to test if an object is of a specified type.

Example :

public class MainClass {
    public static void main(String[] a) {

    String s = "Hello";
    int i = 0;
    String g;
    if (s instanceof java.lang.String) {
       // This is going to be printed
       System.out.println("s is a String");
    }
    if (i instanceof Integer) {
       // This is going to be printed as autoboxing will happen (int -> Integer)
       System.out.println("i is an Integer");
    }
    if (g instanceof java.lang.String) {
       // This case is not going to happen because g is not initialized and
       // therefore is null and instanceof returns false for null. 
       System.out.println("g is a String");
    } 
} 

Here is my source.

Barth
  • 15,135
  • 20
  • 70
  • 105
  • 9
    When using the instanceof operator, keep in mind that null is not an instance of anything. – Sudhakar Feb 16 '15 at 10:57
  • Why don't you use `if`? Now the second and third conditions aren't evaluated since the first is `true`. – Hummeling Engineering BV Jan 26 '18 at 12:55
  • @HummelingEngineeringBV you are actually right, I reacted a bit too fast to the comment of Tim . We do want to evalute each of these conditions. Thank you, edited. – Barth Feb 09 '18 at 14:03