Static Imports
Home ] Up ]

 

 

Starting in Java 5, the import statement was enhanced to allow the import of static methods and fields from a class.

For example:

import static java.lang.System.exit;
import static java.lang.System.out;
import static java.lang.Math.sqrt;
import static java.lang.Math.PI;
public class StaticImportTest
{
  public static void main(String[] args)
  {
    System.out.println("Using System.out.println(...)");
    out.println("Using out.println(...)");

    out.println("The square root of 64 is " + Math.sqrt(64));
    out.println("The square root of 91 is " + sqrt(91));

    out.println("The value of PI is " + PI);
  }
}

which, when run in a Java Virtual Machine supporting Java 5 or above, produces the following output:

Using System.out.println(...)
Using out.println(...)
The square root of 64 is 8.0
The square root of 91 is 9.539392014169456
The value of PI is 3.141592653589793

In a JVM supporting an earlier version of Java than 5, the program will produce compilation errors.

 

This page was last modified on 02 October, 2007