Static Block in Java

It’s a static initializer. It’s executed when the class is loaded (or initialized, to be precise, but you usually don’t notice the difference). It can be thought of as a “class constructor”. Note that there are also instance initializers, which look the same, except that they don’t have the static keyword. Those are run in addition to the code in the constructor … Read more

What is the use of a private static variable in Java?

Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined – that’s because it is defined as private. public static or private static variables are often used for constants. For example, many people don’t like to “hard-code” constants in their code; they like to make a public static or private static variable with a meaningful … Read more

Static Initialization Blocks

The non-static block: Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create. Example: public class Test { static{ System.out.println(“Static”); } { System.out.println(“Non-static block”); } public static void main(String[] args) { Test t = new Test(); Test … Read more