Static Import in Java
In Java, static import is a powerful feature that allows you to access static members (fields and methods) of a class directly without using the class name. This can make your code cleaner, shorter, and easier to read, especially when working with constants or utility methods.
What is Static Import?
Normally, when you access a static member of a class, you must use the class name:
double result = Math.sqrt(16); // Using class name Math
System.out.println(result); // Output: 4.0
With static import, you can call static members directly without the class name:
import static java.lang.Math.sqrt;
public class Demo {
public static void main(String[] args) {
double result = sqrt(16); // Directly use sqrt()
System.out.println(result);
}
}
Output:
4.0
Syntax
import static package.ClassName.staticMember; // Import a specific member
import static package.ClassName.*; // Import all static members
Examples
Import a Specific Static Member
import static java.lang.Math.PI;
public class Circle {
public static void main(String[] args) {
System.out.println("Value of PI: " + PI);
}
}
Output:
Value of PI: 3.141592653589793
Import All Static Members of a Class
import static java.lang.Math.*;
public class MathExample {
public static void main(String[] args) {
System.out.println(sqrt(25)); // Directly use sqrt()
System.out.println(pow(2, 3)); // Directly use pow()
}
}
Output:
5.0
8.0
Real-World Example – Calculating Circle Area
import static java.lang.Math.*;
public class CircleArea {
public static void main(String[] args) {
double radius = 5;
double area = PI * pow(radius, 2); // Use PI and pow() directly
System.out.println("Area of circle: " + area);
}
}
Output:
Area of circle: 78.53981633974483
Points About Static Import :
- Introduced in Java 5.
- Makes code cleaner and reduces class name repetition.
- Only works with static members (fields and methods).
- Overuse can reduce code readability — use selectively.
Advantages
- Cleaner and shorter code.
- Easier to read when using constants or utility methods frequently.
- Useful in unit testing frameworks like JUnit (e.g.,
assertEquals,assertTrue).
Disadvantages / Caution
- Can lead to ambiguity if two static members from different classes have the same name.
- Overuse can reduce readability and maintainability.
- Not suitable for beginners to overuse without care.
Best Practices
- Use specific static imports rather than to avoid confusion.
- Use static import mainly for constants and utility methods.
- Avoid overusing in large projects to maintain clarity.
