The static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.
The BlockTest class has two static blocks, which are executed when the class is loaded by the JVM. The staticBlocks class also has two static blocks, which are executed when the class is loaded by the JVM. The main method creates an instance of the BlockTest class, which causes its static blocks to be executed. Then, the "Main" message is printed to the console.
When the staticBlocks class is loaded by the JVM, the static blocks are executed in the order in which they appear in the code. Therefore, "Block-1" is printed first, followed by "Block-2". When an instance of the BlockTest class is created, its static blocks are executed in the same way. Therefore, "BlockTest-1" is printed first, followed by "BlockTest-2".
//Static Blocks in Java class BlockTest { static { System.out.println("BlockTest-1"); } static { System.out.println("BlockTest-2"); } } public class staticBlocks { static { System.out.println("Block-1"); } public static void main(String[] args) { BlockTest o =new BlockTest(); System.out.println("Main"); } static { System.out.println("Block-2"); } }
Block-1 Block-2 BlockTest-1 BlockTest-2 MainTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions