Understanding static Import Syntax
What you'll learn: How to use static imports to bring class members directly into your code's namespace, eliminating repetitive class name prefixes.
The Core Idea
So far, you've accessed static members using the fully qualified class name:
Math.sqrt(25);
System.out.println("Hello");
Static imports let you skip the class name and use static fields and methods directly, as if they were declared in your own class:
sqrt(25); // No Math. prefix needed!
println("Hello"); // No System.out. prefix needed!
Think of it like adding someone's tools to your own toolbox temporarily. Instead of saying "use Bob's hammer," you can just say "use hammer" because it's now in your workspace.
The Syntax
Import a Single Static Member
import static java.lang.Math.sqrt;
// Now you can write:
double result = sqrt(25);
Import All Static Members from a Class
import static java.lang.Math.*;
// Now you can use any Math method without the prefix:
double a = sqrt(16);
double b = abs(-10);
double c = PI; // static field
How It Differs from Regular Imports
-
Regular import: Brings a class into scope so you don't need the package name
import java.util.ArrayList;→ useArrayListinstead ofjava.util.ArrayList
-
Static import: Brings static members into scope so you don't need the class name
import static java.lang.Math.sqrt;→ usesqrt()instead ofMath.sqrt()
Key Takeaway: Static imports use import static and bring individual static fields or methods into your namespace, letting you use them without the class name prefix—but use them sparingly to avoid confusion about where members come from.