Tuesday, July 14, 2009

Static Imports in Java 5

One reason of introducing static imports in java is to reduce keystrokes. Although, this is not the only reason, static imports are used when you want to use static members of a class. For example, if you want to use static fields and methods of Math class, you use it as Math, a dot operator (.), followed by a field or method name. Static import declarations enable programmers to use static members of a class as if they were declared in the same class. Class name and dot operator are not required in this case.

Forms of static imports

Static Imports in java comes in two forms:

  • Import a particular static member of a class.

    import static packageName.className.staticMemberName;
    for ex. java.lang.System.out;
  • Import all static members of a class.

    import static packageName.className.*;
    for ex. java.lang.Integer.*;

Let’s look at the static imports with a simple example:

Without using static imports

public class WithoutStaticImportProg {
public static void main(String[] pmt) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}

Using static imports

import static java.lang.System.out;
import static java.lang.Integer.*;
public class StaticImportProg {
public static void main(String[] pmt) {
out.println(MAX_VALUE);
out.println(toHexString(42));
}
}

Both classes produce the same output:

2147483647
2a

Points to remember for static imports:

  • If you use static import for MAX_VALUE member for both Integer and Long class in the same program, you will get a compilation error, since both have a MAX_VALUE constant. Java won’t come to know which class MAX_VALUE you are talking about.
  • Static imports can only be used with static object references, constants (as they are static and final), and static methods.
  • You can use import static; you can’t say static import.

No comments:

Post a Comment