Sitelet https://java2blog.com/java-static-import-example/#respond

Java static import example

If any class which is not in same package, we need to import it. If we import that class we can directly access static variables and methods with the class name.

If you use static import,  you do not need to use class name any more.

Lets understand with the help of example

Without using static import :

package org.arpit.java2blog;

public class StaticImportMain {

    public static void main(String[] args) {
        System.out.println("With Static import");
        System.out.println("Value of PI : "+Math.PI);
    }

}

With using static import :

package org.arpit.java2blog;
import static java.lang.System.out;
import static java.lang.Math.PI;

public class StaticImportMain {

    public static void main(String[] args) {
        out.println("With Static import");
        out.println("Value of PI : "+PI);
    }

}

As you can see, we have directly used out.println and PI without using class name because  we have used static import here.

Advantages:

If you have lot of static variables, you have to write less code.
 
Disadvantages:
 
It is very hard to read and unmaintainable.


[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.