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
394 views
in Technique[技术] by (71.8m points)

java - What does `public static void main args` mean?

I am not sure what this means, whenever before you write a code, people say this

public static void main(String[] args) {

What does that mean?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is a little bit detailed explanation on why main method is declared as

public static void main(String[] args)

Main method is the entry point of a Java program for the Java Virtual Machine(JVM). Let's say we have a class called Sample

class Sample {
     static void fun()
     {
           System.out.println("Hello");       
     }  
 }

class Test {
      public static void main(String[] args)
      {
                Sample.fun();
      }  
}

This program will be executed after compilation as java Test. The java command will start the JVM and it will load our Test.java class into the memory. As main is the entry point for our program, JVM will search for main method which is declared as public, static and void.

Why main must be declared public?

main() must be declared public because as we know it is invoked by JVM whenever the program execution starts and JVM does not belong to our program package.

In order to access main outside the package we have to declare it as public. If we declare it as anything other than public it shows a Run time Error but not Compilation time error.

Why main must be declared static?

main() must be declared as static because JVM does not know how to create an object of a class, so it needs a standard way to access the main method which is possible by declaring main() as static.

If a method is declared as static then we can call that method outside the class without creating an object using the syntax ClassName.methodName();.

So in this way JVM can call our main method as <ClassName>.<Main-Method>

Why main must be declared void?

main() must be declared void because JVM is not expecting any value from main(). So,it must be declared as void.

If other return type is provided,the it is a RunTimeError i.e., NoSuchMethodFoundError.

Why main must have String Array Arguments?

main() must have String arguments as arrays because JVM calls main method by passing command line argument. As they are stored in string array object it is passed as an argument to main().


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

...