Java instanceof operator details


Home - Tutorials - Basics

This tutorial demonstrates how to use the instanceof keyword in Java to test the object type.

Tutorial info:


Name:Java instanceof operator details
Total steps:1
Category:Basics
Date:2011-04-09
Level:Beginner
Product:See complete product
Viewed:7896

Bookmark Java instanceof operator details



AddThis Social Bookmark Button

Step 1 - Using Java instanceof operator


Java instanceof operator details

It can happen that you don’t know the exact type of the object you are working with but it would be very important to get this information. In such cases you can use the instanceof keyword. Instance of is not a function but it is an operator. Using the instanceof operator you can check if the actual object is the type you are expecting of.

Let’s see the following basic class hierarchy:

Code:
  1. public class Animal {
  2.  
  3.     public void run() {
  4.         System.out.println("Run");
  5.     }
  6. }
  7.  
  8. public class Dog extends Animal {
  9.  
  10.     public void bark() {
  11.         System.out.println("Bark");
  12.     }
  13. }

Now create some objects and test how the instanceof operator works. Note that how the parent-child relationship works in case of using instanceof. 

Code:
  1. public class InstanceofTest {
  2.     public static void main(String[] args) {
  3.         Animal cat = new Animal();
  4.         Animal dog = new Dog();
  5.         Dog rottweiler = new Dog();
  6.         String text = "This is a string object";
  7.  
  8.         testObjectType(cat);
  9.         testObjectType(dog);
  10.         testObjectType(rottweiler);
  11.         testObjectType(text);
  12.     }    
  13.  
  14.     public static void testObjectType(Object o){
  15.         System.out.println("--- Test object type of " + o.getClass() + " ---");
  16.         if (o instanceof Animal) {
  17.             System.out.println("The object is an Animal");
  18.         }
  19.         if (o instanceof Dog) {
  20.             System.out.println("The object is a Dog");
  21.         }
  22.         if (o instanceof String) {
  23.             System.out.println("The object is a String");
  24.         }
  25.     }
  26. }

 






Tags: java instanceof operator, java instanceof, instanceof operator, java, instanceof, operator

Java instanceof operator details - Table of contents
Step 1 - Using Java instanceof operator



F1 Site Family
AJAX F1
CSS F1
Database F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.1513