Java - Static Import Declarations

What is Static Import Declaration?

Static import declaration imports static variables/methods of a type into a compilation unit.

Type of static import

A static import declaration have two types: single-static import and static-import-on-demand.

  • A single-static import declaration imports one static member from a type.
  • A static-import-on-demand declaration imports all static members of a type.

Syntax

The general syntax of static import declaration is as follows:

Single-static-import declaration:

import static <package name>.<type name>.<static member name>;

Static-import-on-demand declaration:

import static <package name>.<type name>.*;

Example

Import out field from System class.

Demo

import static java.lang.System.out;

public class Main {
        public static void main(String[] args) {
                out.println("Hello static import!");
        }/*from   w  w  w . ja  v a 2  s.co m*/
}

Result

Import static math method using the following static-import-on-demand declaration:

Demo

import static java.lang.System.out;
import static java.lang.Math.*;

public class Main {
  public static void main(String[] args) {
    double radius = 12.3;
    double area = PI * radius * radius;

    out.println("Value of PI is: " + PI);
    out.println("Radius of circle: " + radius);
    out.println("Area of circle: " + area);
    out.println("Square root of 2.0: " + sqrt(2.0));
  }/*from w w w  .  j a  v a2  s  .  c  om*/
}

Result

Related Topic