# Get the class name for various objects in Java

Java 8Object Oriented ProgrammingProgramming

The getName() method is used to get the names of the entities such as interface, class, array class, void etc. that are represented by the class objects. These names are returned in the form of a string. The getPackage() method gets the package for the given class.

A program that gets the class name for various objects is given as follows −

## Example

Live Demo

package Test;
import java.io.IOException;
import java.util.HashMap;
public class Demo {
public static void main(String args[]) throws IOException {
Object obj = "string";
System.out.println("The class name is: " + obj.getClass().getName());
obj = new HashMap();
System.out.println("The class name is: " + obj.getClass().getName());
Boolean bool = new Boolean(false);
obj = bool;
System.out.println("The class name is: " + obj.getClass().getName());
System.out.println("The package name is: " + Demo.class.getPackage());
}
}

## Output

The class name is: java.lang.String
The class name is: java.util.HashMap
The class name is: java.lang.Boolean
The package name is: package Test

Now let us understand the above program.

The getName() method is used to get the names of various objects such as a String object, HashMap object, Boolean object etc. Then the getPackage() method is used to get the package for the given class which is Test.

Published on 09-Jan-2019 13:12:57