Single Static Import vs Static Import on Demand
What you'll learn: How to choose between importing one static member or using a wildcard to import all static members from a class.
The Two Flavors of Static Import
When you need to use static members (fields or methods) from another class, you have two choices:
Single static import brings in exactly one static member:
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
Static import on demand uses the wildcard * to import all static members from a class:
import static java.lang.Math.*;
How They Work in Practice
With single static import, you explicitly list each member you want:
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
public class Circle {
public static void main(String[] args) {
double radius = 5.0;
double area = PI * sqrt(radius * radius);
System.out.println(area); // PI and sqrt directly available
}
}
With static import on demand, all static members become available:
import static java.lang.Math.*;
public class Circle {
public static void main(String[] args) {
double radius = 5.0;
double area = PI * sqrt(radius * radius);
// PI, sqrt, cos, sin, abs, max... ALL available
System.out.println(area);
}
}
Which Should You Use?
Single static import is generally preferred because:
- It makes your code's dependencies explicit
- Readers immediately see which members come from where
- Reduces risk of name conflicts
Static import on demand is convenient when you use many members from one class, but it can make code harder to understand—someone reading sqrt(x) must guess it came from Math.
Key Takeaway: Use single static imports for clarity and maintainability; reserve static import on demand for cases where you use many members from a single, obvious source.