Differences between building blocks of code, static code blocks, and local code blocks in Java

Source: Internet
Author: User

classstaticcode{intAge ; //Static code block    Static{System.out.print ("Static"); }    //Building Code Blocks{System.out.print ("55"); }        //constructor FunctionStaticcode (intAge ) {         This. age=Age ; System.out.print ( Age+","); }    voidShow () {//Local code block        {            intAge=30; } System.out.print ("Show:" +age+ ","); }}classstaticcodedemo{ Public Static voidMain (string[] args) {staticcode P1=NewStaticcode (20);        P1.show (); Staticcode P2=NewStaticcode (20); }} 

Execution Result: static,55,20,show,55,20
Analysis:
1, first execute Staticcode this class, so static
2. Create P1 object, execute construct code block, 55
3. Perform constructor initialization, 20
4, Executive P1.show (), show:20
5. Create P2 object, execute construct code block, 55
6. Perform constructor initialization, 20

Summary: The static code block is loaded only once, as the class is loaded. The function is to initialize the class.
Constructs a block of code that can be initialized for all objects. The creation of several objects is called several times, which is the initialization of generality for the object.
A constructor is a targeted initialization of a corresponding object.
A local code block defines the life cycle of a variable in a function, age=30 the local code executes. It's automatically released.

Differences between building blocks of code, static code blocks, and local code blocks 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.