Tags

, ,

The most common features that most familiar in Java 5 are, Enhanced for-loop, var-args, typesafe enum, generics, autoboxing. Apart from these language specific changes, there are many classes added in Java 1.5 for security, performance, collections framework, threading, queue, JVM tuning etc.

Static Import is one of the feature among them and here is an example for that.

Static import helps to call the static methods in your class without specifying the class name. The best usecase to use this is with the constants. You can include constants into your code without referring its class in which the constants defined. For example, if you are using Integer.MAX_VALUE or some other constants field of class java.lang.Integer then you could simply use the following static import statement,

Static import

import static java.lang.Integer.*;
class Demo{
public static void main(String [] a){
System.out.println(MAX_VALUE+MIN_VALUE);
}
}

You no need to specify the class name here. You can use this to your application specific constants as well.  The code without static import will be like below.

Code without static import

import java.lang.Integer.*;
class Demo{
public static void main(String [] a){
System.out.println(Integer.MAX_VALUE+Integer.MIN_VALUE);
}
}

Use cases

As per the java document, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import.

The promptly imported static code makes your code more readable, by removing the boilerplate of repetition of class names.

If you are using it other than constants for your application, it will confuse the programmer to understand the source since the programmer cannot check the import each time for variables.

Advertisements