In Java, static import concept is introduced in the 1.5 version. With the help of static import, we can access the static members of a class directly without a class name or any object.
Example:
we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static import we can access sqrt() method directly as shown below
Example:
import static java.lang.Math.*;
class StaticImportExample {
public static void main(String[] args)
{
System.out.println(sqrt(6));
System.out.println(pow(3, 3));
System.out.println(abs(7.4));
}
}
Output:
>>> 36
>>> 27
>>> 7
When we import two static members having the same name but imported from multiple different classes, the compiler will throw an error, as it will not be able to determine which member to use in the absence of class name qualification.
Example:
Here MAX_VALUE is imported from Integer and Byte.
import static java.lang.Integer.*;
import static java.lang.Byte.*;
class AmbiguousImport {
public static void main(String[] args)
{
System.out.println(MAX_VALUE);
}
}
Output:
>>> Error: Reference to MAX_VALUE is ambiguous
Less coding is required if you have access any static member of a class oftenly.
If you overuse the static import feature, it makes the program unreadable and unmaintainable.
According to SUN Microsystem, it will improve the code readability and enhance coding. But according to programming experts, it will lead to confusion and is not good for programming. If there is no specific requirement then we should not go for static import.