About static blocks of code in Java

Source: Internet
Author: User

A. Static code block

① Features: As the class is loaded and executed only once, no matter how many times the object instance is created, the static block of code in this class is only executed once when the class instance is first created or when the static method is called directly using the class name, and if the first time you call a static method using the class name, Static code blocks are executed before the corresponding method is executed. (This also means that when you create a class instance or call a static method using the class name, the class is loaded into memory). If it is Staticcode s=null, such a declaration statement, the class is not loaded into memory.

② function: Used to initialize a class (not an object)

Two. Static method: ① If you simply create an object that contains a class with a static method and do not call a static method, the static method will not execute, and the main method in the main class is executed after executing the static block of code in the main class ②;

Two. Building code blocks

① form:

{System.out.println ("I am Building code block"); }

② function: Used to initialize an object, that is, every time a new object is created, it is executed once, and the order of execution is before the constructor.

About static blocks of code in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.