Java Essential Tips: Static Import

Static Import

Static import is a mechanism to 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:

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

Note that the normal import has the following syntax:
[java]import packagename.*;
import packagename.classname;[/java]
whereas, static import has the following syntax:
[java]import static packagename.classname.*[/java]
For example,
[java]import static java.lang.Math.*[/java]
If you use the above static import in your class, then you could use PI and E constants without referring its class name ie. Math.PI, check the following code:
[java]System.out.println(PI);[/java]

Permanent link to this article: https://blog.openshell.in/2012/01/java-essential-tips-static-import/

Leave a Reply

Your email address will not be published.