Home >Java >javaTutorial >A brief introduction to the execution of static code blocks in Java

A brief introduction to the execution of static code blocks in Java

黄舟
黄舟Original
2017-09-21 10:29:191637browse

This article mainly introduces you to the relevant information about the execution of static code blocks in Java. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it can follow it below. Come and learn with me.

Preface

Generally, if some code must be executed when the project starts, you need to use static code blocks. This This kind of code is actively executed; it needs to be initialized when the project is started. When other programs call it without creating an object, it needs to use a static method. This kind of code is passively executed. The static method is loaded in the class. It is already loaded at the time and can be called directly using the class name.

For example, the main method must be static, which is the program entry point

The difference between the two is:

  • static Code blocks are executed automatically;

  • static methods are executed when called.

Questions and Summary

About static code blocks is actually a common question asked during interviews. Although I roughly knew it when asked during the interview, I still stepped on a small pit when using it. I want to trigger the call of the static code block by calling the static variable of the class, but without success.

Summarize the conditions under which static code blocks can be executed:

Initialize the object for the first time

Call the static method for the first time

First call to the static variable under the static code block


   public class ConfigHandler {
     public static p1 = “p1”;

     static{
      System.out.println("this is a static code block");
     }

     public static p2 = “p2”;
     public static p3 ;

     public static init(){}
   }

staticSystem.out.println("this is a static code block");The situations that can be executed are as follows:

  • new ConfigHandler();

  • System.out.println(ConfigHandler.p2);

  • ##System.out.println(ConfigHandler.p3)

  • ConfigHandler.init(); //Anywhere in the code

The static code block is not executed when p1 is output. That is, if the static variable in front of the static code block is called, the static code block will not be executed.

Summarize

The above is the detailed content of A brief introduction to the execution of static code blocks in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn