普通代码块就是指直接在方法或是语句中定义的代码块
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.构造代码块
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修饰,常用于给类进行初始化,在加载的时候就执行,并且静态代码块执行一次。
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.局部代码块
作用域:存在方法中
public static void main (string[] args){ { int number = 1; } system.out.println(number);//异常}
以上就是java代码块实例分析的详细内容。
