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

Java 8Object Oriented ProgrammingProgramming

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());
raja
Published on 09-Jan-2019 07:02:49
Advertisements