程序中使用{}括起來(lái)的代碼被稱之為代碼塊露戒,根據(jù)其位置和聲明的不同护蝶,可以分為以下幾類代碼塊:
局部代碼塊
在方法中出現(xiàn)占哟;限定變量生命周期心墅,及早釋放,提高內(nèi)存利用率
{ ? ? ? ?// ?方法中
int a = 10;
System.out.println("局部代碼塊:" + a);
} ? ? ? // ? 執(zhí)行到本行時(shí)代碼塊中內(nèi)部變量已被釋放
System.out.println(a);? // ?局部代碼塊外面不能再訪問(wèn)內(nèi)部變量
構(gòu)造代碼塊
也叫初始化塊榨乎,它在類中方法外出現(xiàn)怎燥;多個(gè)構(gòu)造方法方法中相同的代碼存放到一起,每次調(diào)用構(gòu)造都執(zhí)行蜜暑,并且在構(gòu)造方法前執(zhí)行铐姚。示例如下:
public class Demo {
public static void main(String[] args) {
Student stu = new Student("zhangsan", 23); // ? new幾次 構(gòu)造代碼塊就打印幾次
? ? ? ? ? }
}
class Student{
String name;
int age;
//構(gòu)造代碼塊 (初始化塊)
{ ? ?
System.out.println("構(gòu)造代碼塊"); ? ?// ?構(gòu)造代碼塊先于構(gòu)造方法打印
System.out.println("AAAAAAA"); ? //有參和無(wú)參構(gòu)造方法中的兩個(gè)相同代碼存放到一起,每次調(diào)用構(gòu) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 造都執(zhí)行肛捍,并且在構(gòu)造方法前執(zhí)行隐绵。
}
// 無(wú)參構(gòu)造方法
public Student(){
//System.out.println("AAAAAAA");
}
// ?有參構(gòu)造方法
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("有參的構(gòu)造方法");
//System.out.println("AAAAAAA");
? ? ? ? }
}
代碼打印順序如下:
構(gòu)造代碼塊
AAAAAAA
有參的構(gòu)造方法
靜態(tài)代碼塊
在類中方法外出現(xiàn),并加上static修飾拙毫;用于給類進(jìn)行初始化依许,在加載的時(shí)候就執(zhí)行,并且只執(zhí)行一次缀蹄;一般用于加載驅(qū)動(dòng)峭跳。
public class Demo {
public static void main(String[] args) {
// ?new 兩個(gè)對(duì)象 調(diào)用類中方法。
Student stu1 = new Student("zhangsan", 28);
Student stu2 = new Student("lisi", 27);
? ? ? ? ?}
}
class Student{
String name;
int age;
//靜態(tài)代碼塊
static{
System.out.println("靜態(tài)代碼塊"); ?//只執(zhí)行一次袍患,可從打印結(jié)果中看出坦康。
}
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("有參的構(gòu)造方法");
? ? ? }
}
代碼打印順序如下:
靜態(tài)代碼塊
有參的構(gòu)造方法
有參的構(gòu)造方法
同步代碼塊
代碼塊前加上 synchronized關(guān)鍵字,則此代碼塊就成為同步代碼塊诡延。同步對(duì)象一般為當(dāng)前對(duì)象滞欠,即使用this關(guān)鍵字。
同步代碼塊的格式:
synchronized(同步對(duì)象){
需要同步的代碼肆良;
}