Write a Java program to get the simple name of the class


This is a Java program that demonstrates how to get the name and simple name of a class using the Class.forName() method. The program first imports the ClassNotFoundException class.

In the main() method, the Class.forName() method is used to get the Class object associated with the java.lang.String class. This method throws a ClassNotFoundException if the specified class cannot be found, so the method is declared to throw this exception.

The program then uses the getName() method of the Class object to get the fully qualified name of the class, which includes the package name. This name is printed to the console using the println() method.

Finally, the program uses the getSimpleName() method of the Class object to get the simple name of the class, which is just the class name without the package name. This name is also printed to the console using the println() method.

Source Code

public class Get_Name
{
	public static void main(String[] args) throws ClassNotFoundException
	{
		Class cls = Class.forName("java.lang.String");
 
		System.out.println("Class Name Associated with cls : " + cls.getName());
		System.out.println("Simple Class Name Associated with cls : " + cls.getSimpleName());
	}
}

Output

Class Name Associated with cls : java.lang.String
Simple Class Name Associated with cls : String