Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Static Import in Java

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 505
    Comment on it

    INTRODUCTION:

    Static import in Java allows to import static members of class and use them, as they are declared in the same class, means access any static member of class directly without using class name. Like regular import statements, static import also allows wildcard * to import all static members of a class.

    Key points about Static import:

    1. Main advantage of using static import in Java is saving keystrokes.

    2. Static import statements should not be written as "static import" but as "import static"

    3. 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.

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

    5. One of its disadvantage is if you overuse of the static import feature, it makes the program unreadable & unmaintainable.

    6. one more disadvantage in terms of conflicts, once you use static import Integer.MAX_VALUE than after you can not use MAX_VALUE as variable or constants in you code.

    Example:

    double r = Math.cos(Math.PI * theta);
    or
    System.out.println("This is static import");
    

    The above code when changed using static import is changed to:

    import static java.lang.System.out;
    import static java.lang.Math.PI;
    import static java.lang.Math.cos;
    ...
    double r = cos(PI * theta);
    out.println("This is static import");
    

    Reference:

    http://javarevisited.blogspot.in/2012/10/what-is-static-import-in-java-5-example-tutorial.html

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: