What would getPackage() return for a primitive or array 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 primitive or array in unnamed package. A program that demonstrates this is given as follows −

Example

 Live Demo

public class Main {
   public static void main(String[] argv) throws Exception {
      Package pack1 = int.class.getPackage();
      System.out.println(pack1);
      Package pack2 = int[].class.getPackage();
      System.out.println(pack2);
   }
}

Output

null
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 pack1 and pack2 as they are for a primitive data type and an array respectively. A code snippet which demonstrates this is as follows −

Package pack1 = int.class.getPackage();
System.out.println(pack1);
Package pack2 = int[].class.getPackage();
System.out.println(pack2);
raja
Published on 09-Jan-2019 07:05:08

Advertisements