What is static import in Java

What is static import in Java?

Before going to the specific answer of our topic, we can go through the feature “import” in java.

Before the world of “import”

We all know that java uses packages to categories classes and interfaces. Packaging gives a convenient way for namespacing of the classes and interfaces. So the actual way of using a class/interface in another class is by specifying the fully qualified name like package.classname. An example is given below.

Looks weired; Isn’t it? It is not easy to code in this way. We can avoid using the fully qualified name by the use of import statement. So lets rewrite the above code as follows using the import statement.

So we can conclude that the import enables a class/interface to access another class/interface without using their fully qualified name.

Ok, now come to our topic – static import. This feature is added to java from version 5. static import takes us a step ahead of usual import. static import enables a class/interface to access another classe’s/interface’s static member without using their fully qualified name.

There are two purposes we can use a static import for.

  1. Static import to use member function

    We all know the statement String.valueOf(). The valueOf is a static method in the class java.lang.String. We can rewrite the usage of the method with static import as follows.

  2. Static import to use member variable

    We can use the static member variable of a class without their class reference as we used for static member functions.
    Consider the following example

    in the above example, the MAX_VALUE is from Integer class which developers usually writes as Integer.MAX_VALUE

Advantages of static import

The only advantage you can see is that you can reduce the key strokes to write code.

Disadvantages of static import

  • static import does not increase the readability of the code as expected. In the above example Integer.MAX_VALUE gives more clarity than just MAX_VALUE to the programmer.
  • In some cases, same static variable name may be used in two different classes and we cannot “static import” those two together. For example MAX_VALUE is defined in both java.lang.Integer and java.lang.Long. So you cannot “static import” these two and use MAX_VALUE together. It will throw compilation error. More specifically, the code below does not compile.

So thats about static import in java.

Leave a Comment

Your email address will not be published. Required fields are marked *