Clean • Professional
In Java, static import is a powerful feature that allows you to access static members (fields and methods) of a class directly without using the class name. This can make your code cleaner, shorter, and easier to read, especially when working with constants or utility methods.
Normally, when you access a static member of a class, you must use the class name:
double result = Math.sqrt(16); // Using class name Math
System.out.println(result); // Output: 4.0
With static import, you can call static members directly without the class name:
import static java.lang.Math.sqrt;
public class Demo {
public static void main(String[] args) {
double result = sqrt(16); // Directly use sqrt()
System.out.println(result);
}
}
Output:
4.0
import static package.ClassName.staticMember; // Import a specific member
import static package.ClassName.*; // Import all static members
import static java.lang.Math.PI;
public class Circle {
public static void main(String[] args) {
System.out.println("Value of PI: " + PI);
}
}
Output:
Value of PI: 3.141592653589793
import static java.lang.Math.*;
public class MathExample {
public static void main(String[] args) {
System.out.println(sqrt(25)); // Directly use sqrt()
System.out.println(pow(2, 3)); // Directly use pow()
}
}
Output:
5.0
8.0
import static java.lang.Math.*;
public class CircleArea {
public static void main(String[] args) {
double radius = 5;
double area = PI * pow(radius, 2); // Use PI and pow() directly
System.out.println("Area of circle: " + area);
}
}
Output:
Area of circle: 78.53981633974483
assertEquals, assertTrue).