Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, August 10, 2021

What is static import in Java with Example

Static import in Java allows importing static members of the class and use them, as they are declared in the same class. Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods. Many programmers think that using static import can reduce code size and allow you to freely use static field of external class without prefixing class name on that. For example, without static import, you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE but by using static import you can import Integer.MAX_VALUE and refer it is MAX_VALUE.

Similar to regular import statements, static import also allows wildcard * to import all static members of a class. In the next section, we will see the Java program to demonstrate How to use static import statements to import static fields.

Static import example in Java

What is static import in Java 5 with ExampleIn this static import example, we have imported constants Integer.MAX_VALUE and Integer.MIN_VALUE statically and printing their value without prefixing class name on that.

package test;
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
 * Java program to demonstrate How to use static import in Java 5
 * By using static import you can use static field of external class
 * as they are declared in the same class.
 * @author Javin Paul

public class StaticImportExample {

    public static void main(String args[]) {
       //without Static import
        System.out.println("Maximum value of int variable in Java without " +  
                            "static import : "  + Integer.MAX_VALUE);
        System.out.println("Minimum value of int variable in Java without " +
                            static import : " + Integer.MIN_VALUE);
        //after static import in Java 5
        System.out.println("Maximum value of int variable using " +
                            static import : " + MAX_VALUE);
        System.out.println("Minimum value of int variable using" +
                            static import : " + MIN_VALUE);

Maximum value of int variable in Java without static import : 2147483647
Minimum value of int variable in Java without static import : -2147483648
Maximum value of int variable using static import : 2147483647
Minimum value of int variable using static import : -2147483648

If you look at import statements import static java.lang.Integer.MAX_VALUE, its written as import static rather than static import, so just beware of that. We are not using * wildcard here and importing only selected static members but you can also use import static java.lang.Integer.* to import all static fields in one go.

Advantages of Static Import in Java

The main advantage of using static import in Java is saving keystrokes. If you are frequently using System.out.println() statements and tried of typing it, you can statically import System.out or System.* and subsequently you can type out.println() in your code, Though I would suggest using this Eclipse shortcut to generate System.out.println statement which is much faster than static import. 

This is the kind of usage I see one can benefit from static import, other than that static import is just an extension of regular import statement in Java. Similar to the static field you can also import static methods in your class, mostly in the case of Utility classes.

The drawback of Static Import in Java

Many Java programmers argue against static import with a reason that it reduces readability and goes against how static field should be used i.e. prefixed with class name e.g. Integer.MAX_VALUE

Static import has another drawback in terms of conflicts, once you static import Integer.MAX_VALUE you can not use MAX_VALUE as variable in your programmer, the compiler will throw an error. 

Similarly if you static import both Integer.MAX_VALUE and Long.MAX_VALUE and refer them in code as MAX_VALUE, you will get the following compile time error :

Caused by: java.lang.RuntimeException: Uncompilable source code - MAX_VALUE is already defined in a static single-type import 
        at test.StaticImportExample.(
        Could not find the main class: test.StaticImportExample.  Program will exit.
        Exception in thread "main" Java Re


Finally few points worth remembering about static import in Java :

1) Static import statements are written as "import static" in code and not "static import".

2) If you import two static fields with the same name explicitly e.g. Integer.MAX_VALUE and Long.MAX_VALUE then Java will throw compile-time error. But if another static modifier is not imported explicitly e.g. you have imported java.lang.Long.*, MAX_VALUE will refer to Integer.MAX_VALUE.

3) Static import doesn't improve readability as expected, as many Java programmers prefer Integer.MAX_VALUE which is clear that which MAX_VALUE are you referring.

4) You can apply static import statement not only on static fields but also on static methods in Java.

That's all on What is static import in Java 5, What is the advantages and drawbacks of using static import in Java program, and how to use static import in Java. Honestly, it's been almost a decade since Java 5 was released but I have rarely used static import statements. Maybe in the future, I may figure out a strong convincing reason to use static import

Other Java 5 tutorial from Javarevisited


Anonymous said...

Similar to Python. Even I am not in favor as it reduces code readability

Jonathan said...

Logical and best use of static import in Java is visible in Testing framework e.g. JUnit, TestNG and Spring testframework which supports annotation. static importing all Assert methods in Junit e.g. org.junit.Assert.* and using them like asssertEquals() seems perfectly fine to me than Asert.assertEquals(). So if you name properly you can still use static import effectively in Java.

Kabir said...

I was receiving error You can only import static from classes and interfaces, while import @Test annotation for writing JUnit test, please help

Anonymous said...

One of the better use of Java static import, I have seen in recent year is for importing constants. Earlier developer used to use interface to declare constant and later get access to them, by implementing interface, which not only obscure constants in inheritance hierarchy but also defeats whole purpose of using interface for abstraction. By using static import, you can easily find which constant, comes from where, means better readability.

Anonymous said...

Hello, I am trying to import static constant as below, but its giving me compile time error saying "Only a type can be imported, java.nio.file resolves to a package"

import static java.nio.file.*

Can't we import static constants from a package in Java?

Anonymous said...

@Anonymous, No, only static members from a class can be imported using "import static" statements, that includes static fields and static methods. Right way to use static import in your case would be

import static java.nio.file.Files.*

Rama said...

I have static import feature a lot while using unit testing and mocking libraries like Mockito, JUnit, TestNG and others. You can static import key class e.g.

import static org.junit.Assert.*
import static org.mockito.Mockito.*
import static org.mockito.Matcher.*

You can even configure Eclipse content assist to show statically imported method, without even them manually imported, by configuring them in favorites under content assist. Next time, if those libraries in your classpath, typing assert will show all assert methods from jUnit and so on.

Anonymous said...

i didnt understand the drawback as i can use max_value as a variable once i static import Integer.MAX_VALUE ,it is not giving compilation error

manju said...

The main reason why static import was introduced in java was to avoid Constant Interface Anti Pattern.
Google more for Constant Interface antipattern and how static import overcomes it.

Unknown said...

I use 'import static' for importing constant values which are stored in a class, i.e I store properties of database like username, password, url in a class and later I use them by their name instead of classname.username

Post a Comment