Analysis on the execution of static code blocks in Java

preface

Generally, if some code must be executed when the project is started, static code blocks need to be used, and this code is actively executed; It needs to be initialized when the project is started. When other programs call it without creating objects, it needs to use static methods. This code is passively executed. The static methods have been loaded when the class is loaded and can be called directly with the class name.

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

The difference between the two is:

Problems and summary

Static code blocks are actually a common question in the interview. Although I probably know when I asked them in the interview, I still stepped on a small pit when using them. I tried to trigger the call of the static code block by calling the static variable of the class, but it didn't succeed.

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

Initialize object for the first time

First call to static method

The static variable under the static code block is called for the first time

System. In static out. println("this is a static code block"); It can be implemented as follows:

When P1 is output, the static code block is not executed, that is, the static variable in front of the static code block is called, and the static code block will not be executed.

summary

The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>