Monday, October 29, 2012

What is static import in Java 5 with Example

Static import in Java allows to import static members of 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 programmer 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 as MAX_VALUE. Similar to regular import statements, static import also allows wildcard * to import all static members of a class. In next section we will see 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 there 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 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);
    }
}

Output:
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 member but you can also use import static java.lang.Integer.* to import all static fields in one go.

Advantages of Static Import in Java

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 static import System.out or System.* and subsequently you can type out.println() in your code, Though I would suggest to use 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 extension of regular import statement in Java. Similar to static field you can also import static method in your class, mostly in case of Utility classes.

Drawback of Static Import in Java
Many Java programmer argue against static import with 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, compiler will throw 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 following compile time error :

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

Summary
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 same name explicitly e.g. Integer.MAX_VALUE and Long.MAX_VALUE then Java will throw compile time error. But if other 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 programmer 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 advantages and drawbacks of using static import in Java program and how to use static import in Java. Honestly, its been almost a decade with Java 5 released but I have rarely used static import statements. May be in future I may figure out a strong convincing reason to use static import

Other Java 5 tutorial from Javarevisited

9 comments :

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.

Post a Comment