Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Runtime Type Identification in Java

  • Difficulty Level : Medium
  • Last Updated : 22 Feb, 2021

Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.lang. Unlike C++ Java does not support Runtime Type Identification (RTTI) but it provides few methods to find objects at runtime.

Some essential points regarding Runtime Type Identification in Java are following:

  • Determining the type of object at run time not only reduces error but also results in robustness.
  • It is also useful before typecasting any object into another type to avoid run time exception.
  • It is used to implement the type-specific feature on methods that accept types like objects or any interfaces.

The java.lang.Object.getClass() method is used to determine the type of object at run time.


public final Class getClass()

Return Type: Returns the Class objects that represent the runtime class of this object.

Example 1:


// Java Program to determine Runtime type
public class Example1 {
    public static void main(String[] args)
        // Creating the obj
        Object obj = new String("Learn_programming");
        Class abc = obj.getClass();
        // Print the class of obj
        System.out.println("Class of Object obj is : "
                           + abc.getName());
Class of Object obj is : java.lang.String

Example 2:


// Java program to determine object class at run time 
public class Example2 {  
    public static void main(String[] args)   
      // create a new Integer
      Integer num = new Integer(100);
      // print num 
      System.out.println("" + num);
      // print the class of num
      System.out.println("" + num.getClass());


class java.lang.Integer

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!