← Back to Chapters

Java Static Import

? Java Static Import

? Quick Overview

Static import is a Java feature that allows you to access static members (fields and methods) of a class directly without using the class name. It helps reduce repetitive class references and makes code cleaner and more readable.

? Key Concepts

  • Introduced in Java 5
  • Used with static keyword in import statement
  • Applicable only to static members
  • Improves readability when used carefully

? Syntax / Theory

Static import allows direct access to constants or utility methods such as Math.sqrt() without prefixing the class name.

? View Code Example
// Standard import without static import
double result = Math.sqrt(25);
? View Code Example
// Static import of Math.sqrt method
import static java.lang.Math.sqrt;

double result = sqrt(25);

? Code Example(s)

? View Code Example
// Static import of all Math class members
import static java.lang.Math.*;

public class StaticImportDemo {
public static void main(String[] args) {
double value = sqrt(16);
double power = pow(2, 3);
System.out.println(value);
System.out.println(power);
}
}

? Live Output / Explanation

Output

4.0
8.0

The methods sqrt() and pow() are called directly without using the Math class name because of static import.

? Interactive Refactoring

See how code changes when you apply static imports to a Geometry class.

Current: Standard Java Code
public class Geometry {
    public double circleArea(double r) {
        // Repeated usage of "Math."
        return Math.PI * Math.pow(r, 2);
    }
}

✅ Tips & Best Practices

  • Use static import for constants like PI
  • Avoid overusing static imports as it may reduce readability
  • Prefer explicit static imports over wildcard imports
  • Use static import mainly in utility-heavy classes

? Try It Yourself

  • Use static import to access Math.PI directly
  • Compare code readability with and without static import
  • Create your own utility class and use static import