Importing Static Methods and Fields
What you'll learn: How to use import static to call static methods and fields directly, without typing the class name every time.
The Problem with Repeated Class Names
When you call a static method or field, you normally prefix it with the class name:
Math.sqrt(16);
Math.PI;
System.out.println();
If you use these repeatedly, your code becomes verbose. Static imports solve this.
What Is a Static Import?
A static import lets you import individual static members (methods or fields) from a class. Once imported, you can call them directly by name, as if they were defined in your own class.
Syntax:
import static packageName.ClassName.memberName;
Or import all static members from a class:
import static packageName.ClassName.*;
Example: Importing Static Methods
import static java.lang.Math.sqrt;
import static java.lang.Math.PI;
public class Circle {
public static void main(String[] args) {
double radius = 5.0;
double circumference = 2 * PI * radius; // No "Math."
double side = sqrt(25); // No "Math."
System.out.println("Circumference: " + circumference);
System.out.println("Square root: " + side);
}
}
Notice we write PI and sqrt(25) directly, without Math.
When to Use Static Imports
- Heavy use of utility methods (
Math, custom utilities) - Test code with assertion methods
- Constants used frequently
Caution: Overusing import static * can make code less readable—it's unclear where members come from.
Key Takeaway: Static imports let you call static methods and fields without their class name, reducing verbosity when you use the same utilities repeatedly.