See the Tutorial List

Sub Package and Static Import in Java

In this tutorial we will learn about sub-packages in Java and also about the concept of static importa and how it is different from 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 :

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

To Compile: javac -d . Simple.java

To Run: java LearnJava.Package.SubPackage.Simple

Hello 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.

  • The first form of static import statement, import only a single static member of a class

    Syntax:

    import static package.class-name.static-member-name;

    Example:

    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

    Syntax:

    import static package.class-type-name.*;

    Example:

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

Example without using static import

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

12


Example using static import

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

12