Static Import in Java
Formulas full of Math. get hard to read: Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)). A static import brings static members (fields and methods) of a class into scope, so you can write sqrt(pow(a, 2) + pow(b, 2)) instead. It's a small convenience that reads well in the right places and confuses in the wrong ones.
Writing a Static Import
import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
public class Geometry {
public static void main(String[] args) {
double radius = 3;
System.out.printf("Circle area: %.2f%n", PI * pow(radius, 2));
double a = 6, b = 8;
System.out.println("Hypotenuse: " + sqrt(pow(a, 2) + pow(b, 2)));
}
}Circle area: 28.27
Hypotenuse: 10.0How it works
import static java.lang.Math.PI;brings in one static field.PIcan now be used withoutMath..powandsqrtare imported the same way. Note the wordstaticafterimport.import static java.lang.Math.*;would import every static member ofMathat once.
Good Uses
| Use | Example |
|---|---|
| Math-heavy code | sqrt, pow, PI |
| Constants used often | import static java.util.concurrent.TimeUnit.SECONDS; |
| Test assertions | import static org.junit.jupiter.api.Assertions.assertEquals; (testing, later in the course) |
| Factory and builder methods | import static java.util.stream.Collectors.toList; (streams, later in the course) |
In each case the name alone is clear: nobody wonders where assertEquals or sqrt come from.
Ambiguity
If two static imports bring in the same name, using it is a compile error:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;
public class Amb2 {
long limit = MAX_VALUE;
}Amb2.java:5: error: reference to MAX_VALUE is ambiguous
long limit = MAX_VALUE;
^
both variable MAX_VALUE in Integer and variable MAX_VALUE in Long match
1 errorWrite Long.MAX_VALUE instead. And a field or method declared in your own class always shadows a statically imported one with the same name.
Common Mistakes
import static java.lang.Math; A static import names a member (or *), not just a class.
Statically importing everything from several classes. Readers can't tell where names come from, and clashes appear.
Expecting a static import to work for instance methods. Only static members can be statically imported.
Practice
- Easy: Rewrite a program that converts Celsius to Fahrenheit and prints the result with
Math.round, using a static import forround. - Harder: Compute compound interest,
p * pow(1 + r / 100, years), for Rs. 1,00,000 at 7% for 5 years, using static imports forpowandround, and print it rounded to the nearest rupee.
Key Takeaways
Was this tutorial helpful?