Home > Java > javaTutorial > body text

Java code block example analysis

王林
Release: 2023-05-15 10:07:13
forward
823 people have browsed it

1. Ordinary code blocks

Ordinary code blocks refer to code blocks that are defined directly in methods or statements

public class CodeDemo {
 
public static void main(String[] args) {
 
// 普通代码块
               {
int x = 10;	// 局部变量
System.out.println("普通代码块---》"+x);	//10
}
int x = 100;
System.out.println("代码块之外---》"+x);  //100
}
}
Copy after login

2. Construction code block

public class CodeBlock
{       
    {
        System.out.println("构造代码块");
    }
 
    CodeBlock(){
        System.out.println("构造方法");
    }
}
 
public class Test
{
    public static void main(String[] args) {
        CodeBlock codeBlock = new CodeBlock();
 
    }
}
 
//执行结果
//构造代码块
//构造方法
Copy after login

3. Static code block

Appears outside the method in the class and adds static modification, often used to initialize a class, is executed when loading, and the static code block is executed once.

public class CodeBlock 
{
    {
        System.out.println("静态代码块");
    }
 
    {
        System.out.println("构造代码块");
    }
 
    CodeBlock(){
        System.out.println("构造方法");
    }
}
 
public class Test
{
    public static void main(String[] args) {
        CodeBlock codeBlock = new CodeBlock();
    }
}
 
//执行结果
//静态代码块
//构造代码块
//构造方法
Copy after login

4. Local code block

Scope: exists in the method

public static void main (String[] args){
    {
        int number = 1;
    }
    System.out.println(number);//异常
}
Copy after login

The above is the detailed content of Java code block example analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!