iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

練習程式系列 第 4

java,public static void main(String args[ ])

教學來源:
4. Why public static void main(String args[ ]) ? JAVA

有static就可以直接使用class的方法(像是:Ted.name而不用Ted ted = new Ted()在ted.name)。
JVM 就是因為main有static,所以可以直接使用main方法。

如果檔名和class不同,再complier的時候,還是會變成class(類別)檔名。
像是class是t,檔名是a.java:

class t{
    public static void main(String[] args) {
    System.out.println("Hi");
    }
}

javac a.java不會有錯誤,但是產生的檔案還是t.class :
https://ithelp.ithome.com.tw/upload/images/20190904/20111994PiojsH94zR.png

但是如果class是public的,檔名就要和class名一樣。
不然會有錯誤:

錯誤: 找不到或無法載入主要類別 a.java 

https://ithelp.ithome.com.tw/upload/images/20190904/20111994tMh8qPX96I.png

把static拿掉後的錯誤:

錯誤: 主要方法不是類別 t 中的 static,請定義主要方法為:
public static void main(String[] args)

https://ithelp.ithome.com.tw/upload/images/20190904/20111994bRgTSarWg0.png

把void拿掉後的錯誤:

error: invalid method declaration; return type required

https://ithelp.ithome.com.tw/upload/images/20190904/20111994AYirS9RCee.png

把String[] args拿掉後的錯誤:
https://ithelp.ithome.com.tw/upload/images/20190904/20111994wgbu4DoT8k.png

把public拿掉後的錯誤:
https://ithelp.ithome.com.tw/upload/images/20190904/20111994PkhubMbHR5.png

在String[] args放參數

class t{
    public static void main(String[] args) {
      System.out.println("Hi");
      System.out.println("args[0] is "+args[0]); 
      System.out.println("args[1] is "+args[1]); 
      System.out.println("args[2] is "+args[2]); 
    }
}

https://ithelp.ithome.com.tw/upload/images/20190904/201119945nyfojyKwK.png


上一篇
java,JVM vs JRE vs JDK
下一篇
Java 資料型態
系列文
練習程式37
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言