Talking about the execution sequence of Java file and the understanding of main program entrance

  • 2021-07-07 07:38:29
  • OfStack

When we compile the file with the Java suffix through JVM, JVM first looks for the entry (main method)


public static void main(String[] args)

1. Since no object is called at entry time, this method can only be set to static static
2. JVM is the bottom layer of Java, so even if there is a return result, the result has nowhere to go, so this method must be that void has no return value
3. Since the main method is an entry, it is automatically called by JVM. Only when the method is set to the public level of public can it be visible to JVM
To sum up, the entry main method can only be written as


public static void main(String[] args)

When we don't write the main method, the system will automatically add a non-parametric mian main method to us, which is added in the first row of the public class. (As mentioned earlier, the addition is only visible to JVM in the public level and can be automatically called.)

Note: If any public class (public class) is not included in the java file, this file can still be compiled, but because public class cannot be found in active operation, main method cannot be automatically added, JVM cannot find the program entry, and the operation will report an error, that is, the compilation will report an error through operation, and the file lacking public class needs to wait to be called by other java files and cannot be used as an entry.


package j2se;

class X{
  Y y=new Y();
  public X(){
    System.out.print("X");
  }
}
class Y{
  public Y(){
    System.out.print("Y");
  }
}
//public class Z extends X{
 // Y y=new Y();
 // public Z(){
  //   System.out.print("Z");
  // }
  // public static void main(String[] args) {
  //   new Z();
  // }
//}

Error reporting:

Error: The main class j2se. Z cannot be found or loaded
Reason: java. lang. ClassNotFoundException: j2se. Z

When we add the public class (public class), the compilation runs through, and the execution order of the program can be clearly seen according to the returned results. The code is as follows:


package j2se;

class X{
  Y y=new Y();
  public X(){
    System.out.print("X");
  }
}
class Y{
  public Y(){
    System.out.print("Y");
  }
}
public class Z extends X{
  Y y=new Y();
  public Z(){
    System.out.print("Z");
  }
  public static void main(String[] args) {
    new Z();
  }
}

Run result: YXYZ

According to this running result, we can see that after the program runs, the compilation sequence of JVM is as follows, and JVM goes straight to the main () method in public class as the entry, and starts compiling and executing


public static void main(String[] args)

Related articles: