How do I get package name of a class?

To get the package name of a class we can use the getClass().getPackage() method of the inspected object.

package org.kodejava.lang;

import java.util.Date;

public class GetPackageName {
    public static void main(String[] args) {
        // Create an instance of Date class, and then obtain the class package
        // name.
        Date date = new Date();
        Package pack = date.getClass().getPackage();
        String packageName = pack.getName();
        System.out.println("Package Name = " + packageName);

        // Create an instance of our class and again get its package name
        GetPackageName object = new GetPackageName();
        packageName = object.getClass().getPackage().getName();
        System.out.println("Package Name = " + packageName);

Our code printed the following output:

Package Name = java.util
Package Name = org.kodejava.lang