The question is that "Is main() method is compulsory in Java?"
问题是“ main()方法在Java中是强制性的吗?”
Yes, we can write a java program without main() method but there is a condition if and only if java JDK version till JDK 5.
是的,我们可以编写一个没有main()方法的Java程序,但是有一个条件,当且仅当Java JDK版本到JDK 5为止。
Till Java JDK 5 main() method was not compulsory to include in Java program.
直到Java JDK 5 main()方法不是必须包含在Java程序中的。
If we don't write our code in the main() method or don't include main() method in our program then, in that case, we need to write our code under static block then only, in that case, we can execute our code normally as we do.
如果我们不在main()方法中编写代码或在程序中不包含main()方法 ,则在这种情况下,我们只需要在静态块下编写代码,那么在这种情况下,我们可以像我们一样正常执行代码。
Example:
例:
// Java Program to demonstrate till Java JDK5 version
// without main() method is possible.
class WithoutMainMethod {
static {
int i = 2, j = 4, sum;
sum = i + j;
System.out.println("The sum of i and j is :" + sum);
System.out.println("This program is without main() valid till JDK 5 version");
}
}
Output
输出量
E:\Programs>javac WithoutMainMethod.java
E:\Programs>java WithoutMainMethod
The sum of i and j is : 6
This program is without main() valid till JDK 5 version
In the case of the static block is that static block executes before the main() method.
在使用静态块的情况下,该静态块在main()方法之前执行。
Static block executes at the time of class loading.
静态块在类加载时执行。
In the case of the main() method, our program starts executing from the main() method or in other words it is the starting point of the program execution.
对于main()方法 ,我们的程序从main()方法开始执行,换句话说,它是程序执行的起点。
We can call the main() method directly without the creation of an object because it is static.
我们可以直接调用main()方法 ,而无需创建对象,因为它是静态的。
Till Java JDK 5 main() method was not mandated, But from Java JDK 6 main() is mandatory and if we don't include main() method in our program then we will get RuntimeException "main method not found in the class".
直到Java JDK 5 main()方法没有强制执行,但是从Java JDK 6 main()开始是强制性的,如果我们在程序中不包含main()方法 ,则将得到RuntimeException “在类中找不到main方法” 。
Example:
例:
// Program to demonstrate without main() method
// from Java JDK 6 version
class WithoutMain{
int i=2 , j=4 , sum=0;
sum = i + j;
System.out.println("The sum of i and j is :" + sum);
System.out.println("This program without main() is not valid from JDK 6 version");
}
Output
输出量
E:\Programs>javac WithoutMain.java
E:\Programs>java WithoutMain
Error: Main method not found in class WithoutMain, please define the main method as:
public static void main(String[] args)
翻译自: https://www.includehelp.com/java/is-main-method-compulsory-in-java.aspx