代码块
1:普通代码块:直接定义在方法中的代码
    
  
    public class MainDemo01
{
 public static void main(String args[]){
  {
  int c = 40;
 System.out.println(c);
  }
 
 int c =100;
 System.out.println(c);
 }
}
  
  
    
    
    
      输出为:
    
  
F:\java>javac MainDemo01.java
    
      F:\java>java MainDemo01 one
      
       40
      
       100
    
  
2:构造代码块:直接定义在类中的代码
    
    
    
  
    class Demo
{
 {
 System.out.println("构造块");
 }
 public Demo(){
 System.out.println("构造方法");
 }
}
public class MainDemo01
{
 public static void main(String args[]){
  new Demo();
  new Demo();
  new Demo();
  new Demo();
  new Demo();
  }
}
  
  
    
     输出为:
  
    
      F:\java>java MainDemo01
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
    
  
构造块优于构造方法执行,执行多次。
    
    
      3:静态代码块:直接使用static关键字声明的代码
    
  
    
  
    class Demo
{
 {
 System.out.println("构造块");
 }
 static {
 System.out.println("静态代码块");
 }
 public Demo(){
 System.out.println("构造方法");
 }
}
public class MainDemo01
{
 static{
 System.out.println("在主方法中定义的代码块");
 }
 public static void main(String args[]){
  new Demo();
  new Demo();
  new Demo();
  new Demo();
  new Demo();
  }
}
  
  
    
    
    
      输出为:
    
  
    
    
      F:\java>java MainDemo01
      
       在主方法中定义的代码块
      
       静态代码块
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
      
       构造块
      
       构造方法
    
  
得出结论;
1:静态块优先于主方法执行,如果在普通类中定义的静态块,优先于构造块执行,不管有多少实例化对象产生,静态代码块只执行一次,静态代码块的主要功能是为静态属性初始化。
    
    
      能不能不使用主方法就输出“helloworld”呢?
    
  
    
    
      答案是可以的。
    
  
    public class MainDemo01
{
 static{
 System.out.println("helloworld");
 }
}
  
  
    
     输出为:
  
    
      F:\java>java MainDemo01
      
       helloworld
      
       Exception in thread "main" java.lang.NoSuchMethodError: main
    
  
    
    
      可以输出,但是出现错误,程序仍然继续寻找主方法,能不能去掉这个错误呢》
    
  
答案是可以的
    
  
    public class MainDemo01
{
 static{
 System.out.println("helloworld");
 System.exit(1);
 }
}
  
  
    
    
    
      输出为:
    
  
    
    
      F:\java>java MainDemo01
      
       helloworld
    
  

