+ 2

When static block executed in java

7th Jun 2019, 2:07 AM
Dheeraj Mittal🇮🇳
2 Respuestas
+ 1
A static block is executed when the class that contains it is *loaded*. The idea is that any given class is loaded at most once during a Java program's execution. Therefore, static blocks are executed at most once. A class gets loaded the first time it is *used*. That generally means building an instance of it by calling a constructor, or accessing one of its static fields or methods. Other ways are for example by getting a Class introspection object that represents this class. From within the same class, static blocks are executed in the order they appear. Like, if you have several static blocks, the first that comes from the beginning of the class, executes first, then the next that comes and so on. If some constructors or methods or nonstatic blocks appear before or between static blocks, they are ignored in that regards: static blocks are executed one after the other in the order they appear. Static fields, when they contain an initialization, are executed alongside static blocks. That is to say: class Thing { static int a = 3; // executes first static { System.out.println("Hello"); // executes second } static String b = "daydream"; // executes third static { System.out.println("Goodbye"); //executes fourth } }
7th Jun 2019, 7:39 AM
kumesana