Java-code block

Source: Internet
Author: User

code block
Local code block
a local code block is defined in a method or statement  
Features:
A region of code delimited with "{}", at which point you only need to focus on the different scopes
methods and classes delimit boundaries in a code block way .
class demo{
Public static void Main (string[] args) {
{
int x = 1;
System.out.println ("Normal code block" + x);
}
int x =;
System.out.println ("Outside the code block" + x);
}
}
Results:
Common code block 1
outside the code block
Building Code Blocks
Constructing a code block is a block of code that defines the position of a member in a class  
Features:
takes precedence over construction method execution, and constructs code blocks to perform initialization actions that are required for all objects  
Each object that is created executes a block of construction code at a time .   
Public class Person {
private String name;
private int age;

//Construct code block
{
System.out.println ("Construction code block executed");
}
Person () {
System.out.println ("person with parameterless constructor execution");
}
Person (int age) {
this.age = age;
System.out.println ("The constructor of the person (age) argument executes");
}
}
class persondemo{
Public static void Main (string[] args) {
Person p = new Person ();
Person p1 = new Person (at all);
}
}
Static code block
A static code block is a block of code that is defined at the member location , using the static adornment.
Features:
it takes precedence over the execution of the Main method, which takes precedence over the construction of code block execution, when used in any form for the first time to the class.   
The static code block executes only once, regardless of how many objects are created .   
can be used to assign a value to a static variable for initialization of a class.
Public class Person {
private String name;
private int age;
//Static code block
static{
System.out.println ("Static code block executed");
}
}

Java-code block

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.