Static Import
We already know how to work with a package be it user-defined or system-defined. We can easily use the members of a package in our Java programs. But, we might be interested to access the static members of a utility class (where all the fields and methods of the class are static) such as System class or Math class without mentioning its name. The “import static” statement in Java is the option to achieve this.
Advantage: The static import concept greatly enhances the readability of the code and reduces the amount of coding.
This concept is a great addition to the language since Java SE 5. As Java programmers, we may well have written code like the following on more than one occasion:
System.out.println("Hello Java!");
In Java, we can import the static members of a class and refer to them without the usual class name prefix. Thus, we can now do something like this:
import static java.lang.System.out;
out.println("Hello Java!");
Once the static member out is imported, we can use it in our code without the System class prefix. Here’s an even better example from the java.lang.Math class.
// without static import
System.out.println(Math.PI);
System.out.println(Math.sqrt(25.0));
The modified code with static import:
// with static import
import static java.lang.Math.*;
out.println(PI);
out.println(Math.sqrt(25.0));
In the second example, we have used the asterisk (*) to import all of Math class static members in this case.
See the complete program below.
StaticImport.java
import static java.lang.System.out;
import static java.lang.Math.*;
public class StaticImport {
public static void main(String args[]) {
out.println("Hello Java!");
out.println("PI: " + PI);
out.println("SQRT: " + sqrt(25.0));
}
}
Output:
Hello Java!
PI: 3.141592653589793
SQRT: 5.0