Import static elements for more readable Java code

One of the welcome additions to Java language in Java 5 release is the static import declaration. static import works in the same way as traditional import declaration but it imports only the static members of a class.
Traditional import declaration looks like this
import java.util.*;
The above statement will import all the classes under java.util package.

The format of static import declaration is similar with the addition of keyword static. E.g;

import static java.lang.Math.*;

This statement will import all the static members of java.lang.Math class.

Similar to import declaration the static import offers two options. You can import all static members of a class or import only the members that you need in your program.

import static java.lang.Math.PI;
will import only PI.
import static java.lang.Math.*;
will import all static elements from Math class.

Before Java5 to use static fields or methods of a class you had to fully qualify the field/method like

double pi= Math.PI;
double randomNumber = Math.random();

Following is a simple program that uses static members from Math class.

  public class DemoStatic{
    public static void main(String args[]){
         double pi = Math.PI;
         double randomNumber = Math.random();
         System.out.println("PI = " + pi);
         System.out.println("Random = " + randomNumber);
 }
}

Typing fully qualified names quickly become cumbersome if you use lot of static members.


static import eliminates the need of fully qualified names. This not only reduces the number of key strokes for developers it also makes the code more readable.

The above example rewritten with static import will become

  import static java.lang.Math.*;
  public class DemoStatic2{
     public static void main(String args[]){
          double pi = PI;
          double randomNumber = random();
          System.out.println("PI = " + pi);
          System.out.println("Random = " + randomNumber);
     }
}
  

To import a static method you just give the method name without parenthesis.
The only drawback I see with static import is if you import too many static elements from various classes and then use them unqualified in your code it may become hard to determine which element belongs to which class. Used wisely the static import may help you avoid repeating class names over and over.