static imports in java

Many a times we use static methods or constants in our class. For example if you are writing a math library, there are chances that you would need to use lot of math functions from java.lang.Math. for example to calculate the nth power of x you would do

y = Math.pow(x,3);

pow is a static method in the Math class. if you use lot of such Math functions then it makes sense to statically import the Math class.
import static  java.lang.Math.*;
If you do this you can directly use the math functions
y=pow(x,3)

You can also import a specific function or constant
import java.lang.Math.pow;

This statement imports just the pow function.

However, it is advisable to use static imports sparingly since they may render the code difficult to read and maintain.

Leave a Comment