Monday, May 24, 2021

Java Static imports

import statements are used to import code from other packages and classes. Java provides an option to import static elements of a class.For that you have to include the static keyword in the import statement as shown in the below code, this feature is called Static Imports.

In this tiny java bit we will see an example of Static Imports.



import static java.lang.System.*;
import static java.time.LocalDateTime.*;
import java.time.format.DateTimeFormatter;

public class DemoStaticImport {
    public static void main(String args[])
    {
            out.println(now().format(DateTimeFormatter.ISO_DATE));
    }
}


In this example we have two static imports one from System class and the other from LocalDateTime class. if you have observed the code carefully, out.println is used instead of System.out.println. Instead of using LocalDateTime.now() we can access the static method now() without the class name because of the static import.

This code output's today's date in ISO_DATE format.


2021-05-24

No comments:

Post a Comment