概念


在代码加载时,在main()方法执行前,执行静态初始化块中的代码

格式

  1. static{
  2. //代码
  3. }

使用场景


1.读写文件时,打开I/O流
2.操作数据库之前,建立连接
3.……

实例

  1. public class InitBlockStudy {
  2. static {
  3. System.out.println("asdfasdf");
  4. }
  5. public static void main(String[] args) {
  6. System.out.println("我来了哦!!!");
  7. }
  8. }

执行结果:
先打印”asdfasdf”,再打印”我来了哦!!!”