Static import allows you to access the static member of a class directly without using the fully qualified name.
To understand this topic, you should have the knowledge of packages in Java. Static imports are used for saving your time by making you type less. If you hate to type same thing again and again then you may find such imports interesting.
Lets understand this with the help of examples:
Example 1: Without Static Imports
class Demo1{ public static void main(String args[]) { double var1= Math.sqrt(5.0); double var2= Math.tan(30); System.out.println("Square of 5 is:"+ var1); System.out.println("Tan of 30 is:"+ var2); } }
Output:
Square of 5 is:2.23606797749979 Tan of 30 is:-6.405331196646276
Example 2: Using Static Imports
import static java.lang.System.out; import static java.lang.Math.*; class Demo2{ public static void main(String args[]) { //instead of Math.sqrt need to use only sqrt double var1= sqrt(5.0); //instead of Math.tan need to use only tan double var2= tan(30); //need not to use System in both the below statements out.println("Square of 5 is:"+var1); out.println("Tan of 30 is:"+var2); } }
Output:
Square of 5 is:2.23606797749979 Tan of 30 is:-6.405331196646276
Points to note:
1) Package import syntax:
import static java.lang.System.out; import static java.lang.Math.*;
2) Note comments given in the above code.
When to use static imports?
If you are going to use static variables and methods a lot then it’s fine to use static imports. for example if you wanna write a code with lot of mathematical calculations then you may want to use static import.
Drawbacks
It makes the code confusing and less readable so if you are going to use static members very few times in your code then probably you should avoid using it. You can also use wildcard(*) imports.
Leave a Reply