每個 Java 獨立應用程式都必須擁有一個 主類別,其中包含 main 方法作為程式進入點。JVM 啟動後,會尋找並執行此方法,類似 C/C++ 的 main()。
public static void main(String[] args) {
// 程式邏輯從這裡開始
}
public:JVM 能從外部呼叫。static:無需建立實例即可執行。void:不回傳值給 JVM。String[] args:命令列參數陣列。args 陣列包含執行指令後傳入的字串參數:
java MyApp 參數1 參數2 "包含空白的參數"
args[0] = "參數1"args[1] = "參數2"args[2] = "包含空白的參數"public class DrawRect {
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("用法: java DrawRect 寬 高");
System.exit(1);
}
int w = Integer.parseInt(args[0]);
int h = Integer.parseInt(args[1]);
Rectangle rect = new Rectangle(w, h);
rect.drawRect();
}
}
class Rectangle {
private int width, height;
public Rectangle(int w, int h) { width = w; height = h; }
public void drawRect() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) System.out.print("#");
System.out.println();
}
}
}
javac DrawRect.java → 產生 DrawRect.class、Rectangle.classjava DrawRect 10 5 → 輸出 10x5 的矩形| 目標型別 | 轉換方法 | 範例 |
|---|---|---|
int | Integer.parseInt(s) | int n = Integer.parseInt(args[0]); |
long | Long.parseLong(s) | long n = Long.parseLong(args[0]); |
double | Double.parseDouble(s) | double d = Double.parseDouble(args[0]); |
boolean | Boolean.parseBoolean(s) | boolean b = Boolean.parseBoolean(args[0]); |
注意:轉換失敗會拋 NumberFormatException,建議用 try-catch 處理。
複雜 CLI 應用建議使用成熟庫:
# 編譯
javac -d out --module-source-path src $(find src -name "*.java")
# 執行
java --module-path out -m myapp/com.example.Main 參數1 參數2