Java中的main()方法是强制性的吗?
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()方法 ,則在這種情況下,我們只需要在靜態(tài)塊下編寫代碼,那么在這種情況下,我們可以像我們一樣正常執(zhí)行代碼。
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.javaE:\Programs>java WithoutMainMethod The sum of i and j is : 6 This program is without main() valid till JDK 5 versionIn the case of the static block is that static block executes before the main() method.
在使用靜態(tài)塊的情況下,該靜態(tài)塊在main()方法之前執(zhí)行。
Static block executes at the time of class loading.
靜態(tài)塊在類加載時執(zhí)行。
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()方法開始執(zhí)行,換句話說,它是程序執(zhí)行的起點。
We can call the main() method directly without the creation of an object because it is static.
我們可以直接調用main()方法 ,而無需創(chuàng)建對象,因為它是靜態(tài)的。
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()方法沒有強制執(zhí)行,但是從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.javaE:\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
總結
以上是生活随笔為你收集整理的Java中的main()方法是强制性的吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转载] Python中TFTP的理解
- 下一篇: ruby 集合 分组_在Ruby中找到两