instanceof sample program in Java

By: Abinaya Emailed: 1769 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Sometimes, knowing the type of an object during run time is useful. For example, you might have one thread of execution that generates various types of objects, and another thread that processes these objects. In this situation, it might be useful for the processing thread to know the type of each object when it receives it. Another situation in which knowledge of an object's type at run time is important involves casting. In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile time. However, casts involving class hierarchies can produce invalid casts that can be detected only at run time. For example, a superclass called A can produce two subclasses, called B and C. Thus, casting a B object into type A or casting a C object into type A is legal, but casting a B object into type C (or vice versa) isn't legal. Because an object of type A can refer to objects of either B or C, how can you know, at run time, what type of object is actually being referred to before attempting the cast to type C? It could be an object of type A, B, or C. If it is an object of type B, a run-time exception will be thrown. Java provides the run-time operator instanceof to answer this question.

The instanceof operator has this general form:

object instanceof type

Here, object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus, instanceof is the means by which your program can obtain run-time type information about an object.

The following program demonstrates instanceof:

// Demonstrate instanceof operator.
class A {
int i, j;
class B {
int i, j;
class C extends A {
int k;
class D extends A {
int k;
class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instance of A");
if(b instanceof B)
System.out.println("b is instance of B");
if(c instanceof C)
System.out.println("c is instance of C");
if(c instanceof A)
System.out.println("c can be cast to A");
if(a instanceof C)
System.out.println("a can be cast to C");
// compare types of derived types
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if(ob instanceof D)
System.out.println("ob is instance of D");
ob = c; // A reference to c
System.out.println("ob now refers to c");
if(ob instanceof D)
System.out.println("ob can be cast to D");
System.out.println("ob cannot be cast to D");
if(ob instanceof A)
System.out.println("ob can be cast to A");
- 230 -
// all objects can be cast to Object
if(a instanceof Object)
System.out.println("a may be cast to Object");
if(b instanceof Object)
System.out.println("b may be cast to Object");
if(c instanceof Object)
System.out.println("c may be cast to Object");
if(d instanceof Object)
System.out.println("d may be cast to Object");

The output from this program is shown here:

a is instance of A
b is instance of B
c is instance of C
c can be cast to A
ob now refers to d
ob is instance of D
ob now refers to c
ob cannot be cast to D
ob can be cast to A
a may be cast to Object
b may be cast to Object
c may be cast to Object
d may be cast to Object

The instanceof operator isn't needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you're writing generalized routines that operate on objects of a complex class hierarchy.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

very useful example. Thanks for this help.

View Tutorial          By: Saurabh at 2010-04-23 04:50:13
2. View Comment

Nice one....

View Tutorial          By: vinod at 2010-05-06 23:36:15
3. View Comment


View Tutorial          By: Abhinaykumar at 2010-07-06 11:34:53
4. View Comment

nice and simple information...............

View Tutorial          By: sengadu at 2010-07-24 07:43:29
5. View Comment


View Tutorial          By: touraj at 2010-08-11 13:40:33
6. View Comment

please provide Example instanceof With Collections ...
this example... Helpful

View Tutorial          By: siddardha at 2010-08-18 00:30:38
7. View Comment

Excellent example !!!

View Tutorial          By: mah at 2010-11-27 04:06:22
8. View Comment

good one nice

View Tutorial          By: megha at 2011-07-16 15:54:29
9. View Comment

good.....not bad. .show me more programs.

View Tutorial          By: saranya at 2011-12-07 08:49:39
10. View Comment

gr8 help dude thankx a lot:-)

View Tutorial          By: Mr. Bond at 2011-12-09 19:21:36
11. View Comment

Thanks.. grt example
Also... If the type argument is an interface name, java::instanceof returns 1 if the Object argument implements the interface. Otherwise, java::instanceof returns 0.

View Tutorial          By: Shahid at 2011-12-20 10:26:22
12. View Comment

simple and clear , thanks a lot!

View Tutorial          By: Steiner at 2012-01-29 19:44:57
13. View Comment

thank you..!!
really very helpful...

View Tutorial          By: sneha at 2012-01-30 18:01:16
14. View Comment

thank u it hlep me a lot gr8.

View Tutorial          By: harish at 2012-03-31 14:34:50
15. View Comment

Java s ssssss

View Tutorial          By: zoya at 2012-04-27 12:24:59
16. View Comment

Nice example. Thank you very much.

View Tutorial          By: vinod at 2012-06-19 11:19:53
17. View Comment

if(a instanceof C)
System.out.println("a can be cast to C");

How can you cast it please?

Thanks, great tutorial.

View Tutorial          By: John at 2012-07-13 17:34:42
18. View Comment

Great ! done a gud job

View Tutorial          By: Manju at 2012-11-02 06:43:58
19. View Comment

it is a good example thanks

View Tutorial          By: tadeleh at 2012-11-13 12:46:08

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Abinaya
How to compile a Java program - javac
The clone() Method in Java
Data Types in Java
JSP Example to connect to MS SQL database and retrieve records
faces-config.xml to DirectTraffic in the JSF Application
Enabling Expression Language Evaluation in JSP
Using malloc() Function in C
ActionErrors and ActionError in Struts
Open, Creat, Close, Unlink system calls sample program in C
Structures and Functions in C
Introduction to JSP expression language
Multi-dimensional Arrays in C (Explained using date conversion program)
A C program similar to grep command in UNIX
Type Conversions in C (String to Integer, isdigit() etc)
Basics of C

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
Sample Java program shows how to write to COM port using Java.
Vector example in Java
Java File
How to reverse the elements in a Single dimension array and display the output
Fields in JasperReports
instanceof sample program in Java
Transient vs Volatile modifiers in Java
how to use boolean data type in Java
char data type in Java
How to use ArrayList in Java
ThreadGroup Sample in Java
The OOP Principles
Read from a COM port using Java program
Sample Java Script that displays a movable clock
Update contents of a file within a jar file
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet