Java 中 main() 方法的返回型別可以更改嗎?
public static void main() 方法是 Java 程式的入口點。每當你執行一個 Java 程式時,JVM 都會搜尋 main 方法並從那裡開始執行。
你可以將程式中的 main 方法的返回型別寫成非 void 型別,程式也能編譯透過,不會出現編譯錯誤。
但是,在執行時,JVM 不會將這個新的方法(返回型別非 void)視為程式的入口點。
它會搜尋返回型別為 void,且引數為 String 陣列的公共靜態 main 方法。
public static int main(String[] args){ }
如果找不到這樣的方法,就會產生執行時錯誤。
示例
在下面的 Java 程式中,我們嘗試將 main 方法的返回型別寫成整數:
import java.util.Scanner; public class Sample{ public static int main(String[] args){ Scanner sc = new Scanner(System.in); int num = sc.nextInt(); System.out.println("This is a sample program"); return num; } }
輸出
執行此程式會產生以下錯誤:
Error: Main method must return a value of type void in class Sample, please define the main method as: public static void main(String[] args)
廣告