Write a Java Program to Determine the class of an object

In Java programming, determining the class of an object is an essential task.

The class of an object defines the set of properties and methods that the object can use.

In this tutorial, we will discuss how to determine the class of an object in Java.


To determine the class of an object, we can use the getClass() method.

The getClass() method returns an instance of the Class class, which contains information about the object’s class.

We can use this information to determine the name of the class, the superclass, and the interfaces implemented by the object.

Let’s take a look at an example program that demonstrates how to use the getClass() method:

public class DetermineClass {
    public static void main(String[] args) {
        String str = "Hello, World!";
        Integer num = new Integer(10);
        Double dbl = new Double(3.14);
        
        System.out.println("Class of str: " + str.getClass().getName());
        System.out.println("Class of num: " + num.getClass().getName());
        System.out.println("Class of dbl: " + dbl.getClass().getName());
    }
}

In this program, we have three objects of different classes: a String, an Integer, and a Double.

We use the getClass() method to determine the class of each object and print the name of the class using the getName() method of the Class class.

When we run this program, we get the following output:

Class of str: java.lang.String
Class of num: java.lang.Integer
Class of dbl: java.lang.Double

As we can see, the getClass() method returns an instance of the Class class, which contains information about the object’s class.

We use the getName() method of the Class class to get the name of the class.


In conclusion, determining the class of an object in Java is a straightforward task.

We can use the getClass() method to get an instance of the Class class, which contains information about the object’s class.

We can then use this information to determine the name of the class, the superclass, and the interfaces implemented by the object.