Course contentsShow
← Java
Lesson 379 of 2,8709. Static Members and Utility ClassesFree lesson

static Imports with Common Utility Classes

Apply static imports to frequently used classes like Math, Collections, and Arrays for cleaner code.

static Imports with Common Utility Classes

What You'll Learn

You'll learn how to use static imports with frequently used utility classes like Math, Collections, and Arrays to write cleaner, more readable code.


Why This Matters

Java provides several built-in utility classes packed with static methods you'll use constantly. Without static imports, you repeatedly type the class name before every method call. Static imports eliminate this repetition when you're using these methods heavily.


Common Utility Classes Perfect for Static Imports

Math Class

Instead of writing Math.sqrt(), Math.pow(), and Math.PI repeatedly, import them:

import static java.lang.Math.*;

public class Calculator {
    public double calculateHypotenuse(double a, double b) {
        return sqrt(pow(a, 2) + pow(b, 2));  // Clean! No Math. prefix
    }
    
    public double circleArea(double radius) {
        return PI * pow(radius, 2);  // Much more readable
    }
}

Arrays Class

When working with arrays extensively:

import static java.util.Arrays.sort;
import static java.util.Arrays.toString;

public class DataProcessor {
    public void processNumbers(int[] numbers) {
        sort(numbers);  // Instead of Arrays.sort(numbers)
        System.out.println(toString(numbers));  // Instead of Arrays.toString(numbers)
    }
}

Collections Class

For collection manipulation:

import static java.util.Collections.sort;
import static java.util.Collections.reverse;

public void organizeList(List<String> names) {
    sort(names);
    reverse(names);
}

When to Use Static Imports with Utilities

Use static imports when:

  • You call the same utility methods many times in one class
  • The shortened names remain clear in context (e.g., sqrt() in a math-heavy class)
  • It genuinely improves readability

Avoid overusing them when the class name adds clarity!


Key Takeaway: Static imports shine brightest with utility classes like Math, Arrays, and Collections—use them to eliminate repetitive prefixes and create cleaner code when you're calling the same utility methods frequently.