How to use static imports in Java

How to use static imports in Java

Java has a syntax convenience feature for setting static imports. This makes source code development potentially easier.

Tags: command line Internet Explorer Linux utility vbscript


A java development environment, such as a file editor, java compiler (javac) and java runtime environment (JRE/java)

When you have your source file open, you can set static imports in the same block of the file where you write other imports. import statements come after the optional package statement, or if the package statement is omitted, it must be the first non-comment/whitespace line of the file.

You can write static imports for object references, constants, and methods, all of which must be static. Constants are static necessarily. To write a static import, you place it before the class declaration as such:

import static java.lang.System.out;
public class ClassName{

According to standard Java naming conventions, you may have noticed that the commonly used:

System.out.println("Message Text");

has a lowercased out, which is used for writing to standard output. Method names usually have lowercased first characters in their names and parenthesis following their name. out is in fact a static object reference. If you wanted to use a constant, such as AM, DAY_OF_WEEK, or even the static object reference out without having to fully qualify it, you can with static imports.

In the above static imports class example, using java.lang.System.out, out can be used without fully qualifying it. You can then use it like:

out.println("Message Text");

because of the static import. Similarly to import AM, or DAY_OF_WEEK from Calendar, you can use this static import:

import static java.util.Calendar.AM; 
import static java.util.Calendar.DAY_OF_WEEK;


import static java.util.Calendar.*;

It is important to note that naming conflicts will cause a compiler error.