Skip to main content

Posts

Showing posts from May, 2021

Java Static Import With Examples

With Java static import feature, which was added in Java 5, you can access static members (fields and methods defined as public static) of a class without qualifying them with class name. Table of contents How to use static import in Java Java static import example Advantages of using static import Drawbacks of using static import Static import ambiguity How to use static import in Java Generally if you need to access any static member (static field or method) of a class you need to qualify it with the class name. For example syntax for accessing a static method- ClassName.static_method() Static import helps with shortening the syntax required to use a static member. Using static import you can import static member that is needed in the class. Syntax for static import of static field import static package_name.className.static_field; Syntax for static import of static method import static package_name.className.static_method; You can also import

Static Block in Java

Static block in Java is used to initialize the static variables (also known as class variables). To initialize instance variables there are constructors , where error handling or other logic can be used. To provide the same capability for class variables, there are static initialization blocks in Java. Syntax of Java static block A static initialization block is a normal block of code enclosed in braces { } , and preceded by the static keyword . static { // code for initialization goes here } Points about static block in Java Java static block is executed only once, when the class is first loaded. Static block is executed before the execution of the main method starts. Non-static variables can't be accessed with in a Java static block. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are executed in the sequence that they appea