Nov 2, 2012

Java-Android Static Import

Static import as named suggest It is use to import static variables and methods. Normally, we access static methods and variables through qualified reference with the class it come from.


import static <package>.<class>;


import static android.util.Log.*;

Static imports allows us to use static methods and variable without qualified reference. Static imports also support wildcard characters. In below code depicted static import of Log class and Color class.


import android.os.Bundle;
import static android.util.Log.*; // static import
import static*; // static import

public class TestActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        i("TAG","Hello"); // static method without qualified class name
        i("Tag","Red Color :" + RED); // static variable RED without qualified class name


1. With static imports, We can use static variables and methods as local variables and methods.
2. We are not allowed to declare same variable name in class, for example, in above code I can not declare local variable named RED.
If I do, compiler generate "java.lang.ExceptionInInitializerError" Error.
3. Readability : It very personal choice, some developer things that static import increase readability but personally I think static import does not improve readability.
4. Ambiguity static import is not allowed for example import static; and import static some.other.package.RED