Java Five-Oh #2: Static Import

Perhaps one of my favorite Java 1.5 features is the static imports. The way I have explained static import is that it makes available other class members and method as if they were defined locally. If that didn’t make much sense, let me demonstrate it with an example. The java.lang.Math class provides a ton of static helper methods. Each time you want to use the abs() method for example you have to do so as such:

int absolute = Math.abs(-7);

But with the new static import you can make available all of the methods in the Math class in your own class so you don’t have to write out Math every time you want to use the abs() method. So if you static import the Math class you can do this:

int absolute = abs(7);

To declare a static import for the Math class use the following construct:

import static java.lang.Math.*;