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


This is a Java program that demonstrates how to get the package name of a class using the getPackage() method of the Class class.

In the main() method, the program uses the Class.forName() method to get the Class object associated with the java.util.Set class and the java.lang.String class.

The program then uses the getPackage() method of the Class object to get the Package object associated with each class. This method returns the Package object that represents the package of the class.

The program then uses the println() method to print the package names to the console. When the program is run, it will output the package names of the java.util.Set and java.lang.String classes to the console.

Source Code

public class GetPackage
{
	public static void main(String[] args) throws ClassNotFoundException
	{
		Class c1 = Class.forName("java.util.Set");
		Class c2 = Class.forName("java.lang.String");
 
		System.out.println("Package Names .. ");
		System.out.println(c1.getPackage());
		System.out.println(c2.getPackage());
	}
}

Output

Package Names ..
package java.util
package java.lang