Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

legal main method signature in java

class NewClass{
public static void main(String a){
    System.out.print("Hello");
}
}

When I'm trying to execute above code, then it shows an error, main method not found. But when I changed public static void main(String a) to public static void main(String... a) or public static void main(String a[]). Then, it works..!!

So, My question is how many different ways we can write legal main method signature and what this signature public static void main(String... a) means ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply because that's the requirement of Java.

A main method/entry point to a program must be a method declared as public static void main(String[] args). Your method that was declared with a String parameter was similar but not compatible.

An array is not the same as a single String - if someone invoked Java with three command-line parameters, the JVM would create a three-element string array, and then how would it pass this into your method that only takes a single string?

So in that case you were trying to launch a Java program based on a class that did not have an main method to act as an entry point.

(The reason why String... works is because this is syntactic sugar for an array parameter, and compiles down to a method with the same signature.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...