简体   繁体   中英

public static void main(String args[]) why string args[] is compulsory ,why we not use public static void main(Object args[])?

why we not use Object args[] it can also hold any type of data.

class Demo {
    public static void main(Object args[]) {
        System.out.println("hello");
    }
}

Because you cannot pass an object via a command line argument.

The main method receives its arguments from the command line, which in most (all?) OSes is string oriented. In other words, the information that Java will receive to call main , will already be in string form (and only string), so using Object[] for main would require programmers to add explicit casts to String each time they would want to use an argument as a string. Using String[] is therefor more logical, and leads to simpler code.

And of course, as Turing85 said in the comments, the legalistic point of view is that this is "because the JLS says so" :

The method main must be declared public , static , and void . It must specify a formal parameter (§8.4.1) whose declared type is array of String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM