Static Import Statements in Java
Static Import feature was introduced in Java 5. This feature provides a typesafe mechanism to include constants into code without having to reference the class. Although some would argue that it comes at the expense of readability.
When to use Static Imports ?
Static imports can be used when you want to “save typing” while using a class’s static members.
Without static imports
package com.sneppets.corejava; public class StaticExample { public static void main (String[] args){ System.out.println(Integer.MIN_VALUE); System.out.println(Integer.toBinaryString(10)); } }
Output:
-2147483648 1010
After using static imports
package com.sneppets.corejava; import static java.lang.System.out; import static java.lang.Integer.*; public class StaticImportExample { public static void main (String[] args){ out.println(MIN_VALUE); out.println(toBinaryString(10)); } }
Output:
-2147483648 1010
Summary:
- Even though we call this feature as “static import“, the syntax MUST be import static followed by fully qualified name of the static member that you want to import or a wildcard.
- In the above example we wanted to use several of the static members of the java.lang.Integer class. So this static import statement uses the wildcard.
- The benefit of the static import you are seeing here is, firstly we don’t have to type the System in System.out.println statement. Secondly, we don’t have to type the Integer in Integer.MIN_VALUE . Finally, one more shortcut for using method i.e., we don’t have to type Integer in Integer.toBinaryString() .
Rules for using static imports:
- You should say import static and you can’t say static import.
- Watch out for ambiguously named static members. For example static import for both Integer and Lang class referring to MIN_VALUE will result in compile error. Java will not know which MIN_VALUE you are referring to.
- You can do static import on static object references, constants and static methods.