What would getPackage() return for a class in unnamed package in Java?


The package for a class can be obtained using the java.lang.Class.getPackage() method with the help of the class loader of the class.

The getPackage() method returns null for a class in unnamed package. A program that demonstrates this is given as follows −

Example

 Live Demo

class Class1 {
   public class Main {
      public static void main(String[] argv) throws Exception {
      Class c = Class1.class;
      System.out.println(c.getPackage());
   }
}

Output

null

Now let us understand the above program.

The getPackage() method is used to obtain the package for the class. However, the getPackage() method returns null for the class Class1 as it is in unnamed package. A code snippet which demonstrates this is as follows −

Class c = Class1.class;
System.out.println(c.getPackage());

Updated on: 25-Jun-2020

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements