Static imports are used to save your time and typing. If you hate to type same thing again and again then you may find such imports interesting.
The import allows the java programmer to access classes of a package without package qualification.
The static import feature allows to access the static members of a class without the class qualification.
Lets understand this with the help of below 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