Java Program to Find the Class Name of an Object

In this Java program, we will learn to find the class name of an object. In Java, you can determine the class of an object by using the getClass() method, which is a method of the Object class that all Java classes inherit from. The getClass() method returns an instance of the Class class, which provides information about the object's class, including its name and package.

Here is an example of how you can determine the class of an object in Java.


Java Program to Find the Class Name of an Object

public class ClassExample {
  public static void main(String[] args) {
    Object obj = new String("Hello, World!");
    Class objClass = obj.getClass();
    System.out.println("Class name: " +
            objClass.getName());
    System.out.println("Package name: " +
            objClass.getPackage().getName());
  }
}
Output
Class name: java.lang.String
Package name: java.lang

In this example, the main method first creates an Object variable obj and assigns it an instance of the String class. Then it calls the getClass() method on the obj variable, which returns an instance of the Class class, that instance is stored in objClass variable. Next, it calls the getName() method on the objClass variable to get the name of the class, and the getPackage().getName() method to get the package name of the class and prints both to the console.

You can also use the instanceof operator to check if an object is an instance of a certain class, for example:

if (obj instanceof String) {
    System.out.println("obj is an instance of String");
}

It's important to note that the getClass() method returns the class of the object at runtime, not at compile-time. This means that if you have a variable declared as a superclass, and it's assigned an object of a subclass, the getClass() method will return the class of the subclass, not the superclass.

Also, the getName() method returns the fully qualified name of the class, including the package name, whereas getSimpleName() method returns only the name of the class without the package name.