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 } }
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(); } } //执行结果 //构造代码块 //构造方法
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(); } } //执行结果 //静态代码块 //构造代码块 //构造方法
4. Local code block
Scope: exists in the method
public static void main (String[] args){ { int number = 1; } System.out.println(number);//异常 }
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!