static import in Java

To import specific member say class in a package in Java, we use below syntax.

import static java.io.File;

To import all members in a package in Java, we use below syntax.

import static java.io.*;

Both the statements above will import the members in a package like classes, interfaces etc.

With static import, it is possible to import the static members of the class.

For example – to import all static members in Math class, we can use below syntax.

import static java.lang.Math.*;

Below example explain how to use static import in Java.

package static_import;

import static java.lang.Math.*;

public class StaticImport {
    public static void main(String [] args){
        //Without static import, you will have to use 
        //Math.sqrt to invoke method.
        System.out.println("Square root of 625 is - > " + sqrt(625));
    }
}

Here is the output of above Java code.

Square root of 625 is – > 25.0

You may also like...