บล็อกแบบคงที่ดำเนินการเมื่อ classloader โหลดคลาส บล็อกสแตติกถูกเรียกใช้ก่อนเมธอด main() เรามาดูตัวอย่างกัน −
ตัวอย่าง
class Demo{
static int val_1;
int val_2;
static{
val_1 = 67;
System.out.println("The static block has been called.");
}
}
public class Main{
public static void main(String args[]){
System.out.println(Demo.val_1);
}
} ผลลัพธ์
The static block has been called. 67
คลาสชื่อ Demo มีค่าจำนวนเต็มคงที่และค่าจำนวนเต็มปกติ ในบล็อกสแตติก ค่าถูกกำหนด และในคลาสหลัก อินสแตนซ์ของคลาสสาธิตจะถูกสร้างขึ้นและเข้าถึงจำนวนเต็มคงที่จากที่นั่น