Java Static Import:
On this page
What is Static Import?
Introduced in Java 5, static import is a feature that lets you access static fields and methods from another class without needing to qualify them with the class name. This can reduce verbosity in your code and make it more readable, especially when dealing with frequently used constants or utility methods.
Syntax of Static Import
import static packageName.ClassName.staticMember;
To import all static members of a class using the wildcard *:
import static packageName.ClassName.*;
To use static import, you utilize the import static statement.
Java static import Example
package com.example.utils;
public class MathUtils {
public static final double PI = 3.141592653589793;
public static final double E = 2.718281828459045;
public static double square(double value) {
return value * value;
}
public static double cube(double value) {
return value * value * value;
}
}
Main Class with Static Import
Now, let’s use these constants and methods in another class, taking advantage of static import:
package com.example.main;
import static com.example.utils.MathUtils.PI;
import static com.example.utils.MathUtils.E;
import static com.example.utils.MathUtils.square;
import static com.example.utils.MathUtils.cube;
public class Main {
public static void main(String[] args) {
double radius = 5.0;
double area = PI * square(radius);
double volume = cube(radius);
System.out.println("Area of the circle: " + area);
System.out.println("Volume of the cube: " + volume);
}
}