static import java

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

Output:

After using static imports

Output:

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.

Leave a Reply

avatar
  Subscribe  
Notify of