Java Programming

Can anyone explain How can we instanceof keyword in java?

User Avatar
Wiki User
December 17, 2009 12:44AM

The instanceof keyword is very self explanatory: it is used to test if an object is an instance of a particular class.

Example:

// Make a new String object
String str = "123";

// Display a message if str is a String
if (str instanceof String) {
System.out.println("str is a String!");

}


Of course, the above isn't very useful since we already know str is a String. So let's look at another example:

public static void f(Object obj) {
if (obj instanceof String) {
System.out.println("obj is a String!");

} else {
System.out.println("obj is NOT a String!");

}

}

In this example, we have no idea what type of object obj will be. So we test to see if obj is a String or not.


The instanceof keyword was more useful in the past (before Java 1.5) when Java didn't have the idea of generic types in it. Now it's generally considered bad practice to use the instanceof keyword, since it means we don't know what type of objects we're using.