Signup/Sign In

Java Sub Package and Static Import

In this tutorial, we will learn about sub-packages in Java and also about the concept of static import and how it is different from normal import keyword.

Subpackage in Java

Package inside the package is called the subpackage. It should be created to categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.

Note: The standard of defining package is domain.company.package e.g. LearnJava.full.io

Example:

In this example, we created a package LearnJava and a sub package corejava in the Simple.java file.

package LearnJava.corejava;
class Simple{
  public static void main(String args[]){
   System.out.println("Hello from subpackage");
  }
}

To compile the class, we can use the same command that we used for package. Command is given below.

javac -d . Simple.java

To run the class stored into the created sub package, we can use below command.

java LearnJava.corejava.Simple

After successful compiling and executing, it will print the following output to the console.

Hello from subpackage

Static import in Java

static import is a feature that expands the capabilities of import keyword. It is used to import static member of a class. We all know that static member are referred in association with its class name outside the class. Using static import, it is possible to refer to the static member directly without its class name. There are two general form of static import statement.

We can import single or multiple static members of any class. To import single static member we can use statement like the below.

import static java.lang.Math.sqrt;   //importing static method sqrt of Math class

The second form of static import statement, imports all the static member of a class.

import static java.lang.Math.*;   //importing all static member of Math class

Example without using static import

This is alternate way to use static member of the class. In this case, we don’t need to use import statement rather we use direct qualified name of the class.

public class Test
{
    public static void main(String[] args)
    {
        System.out.println(Math.sqrt(144));
    }
}

12

Example using static import

In this example, we are using import statement to import static members of the class. Here, we are using * to import all the static members.

import static java.lang.Math.*;
public class Test
{
    public static void main(String[] args)
    {
        System.out.println(sqrt(144));
    }
}

12