Usage of Static Import In Java with Example

15 Flares Twitter 0 Facebook 0 Google+ 15 LinkedIn 0 Filament.io 15 Flares ×

Since Java 5, static import feature is available. Static import makes it easier to access static fields or methods of a class directly. There is no need to qualify it with the class name. This greatly simplifies the usage of many library and framework functions. For example you are no longer required to use System.out.println() – instead you can simplify it with just out.println() using the static import feature.

Static Import – Example

Static import makes it easier to code, but sometimes too much of its usage can make the code very difficult to read.  Let us take one more example to understand its benefit.

Without static import you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE. By using static import, you can import Integer.MAX_VALUE and refer it as MAX_VALUE.  Another example is the use of constants in java.lang.Math.* package – A static import of java.lang.Math.* would allow a class to replace Math.sqrt with just sqrt.

Static Import – Example 2

We have used sqrt function of java.lang.Math package and the out.printl() of System.lang directly without using the Class qualifier. I think you can judge yourself whether this is useful or makes the code difficult to read ( when you use too much of it).