Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
After almost 1 year working with Java,I still can not explain properly to others or myself why we need this, and how it works.
Obviously, I know what each of keywords does independantly, but I am not sure about the whole thing.
Can someone please describe it in very simple language?
Public : is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or variable is not instance related but Class related. It can be accessed without creating the instance of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only.
String args[] : is the parameter to the main Method.
The other answers are correct, but I'll try to state it in English.
When you create a program, java needs to know where to start the program, so they use this as an entry point. Since it's static method, there doesn't need to be an instantiation of the class. It can simply call that method and know that that's where the program starts.
I knew these already thank you for you response and downvotes.
public
It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in you current class.
static
When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
void
Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
main
It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
String args[]
These are the arguments of type String that your Java application accepts when you run it.
But why there is no simplar method to call main like in other languages, and why we need to get argument and store as String while we sometimes only call methods in the main.
When you start a Java program the JVM needs to know where it should start the execution of the whole thing. This is not obvious because there are thousands of Java classes available on the classpath.
That's why you must give the name of one particular Java class in your command line. For example
java com.stackoverflow.example.Main bla blah
The JVM then just loads this class, looks for its static void main(String[] args) method, and calls it with the remaining parameters taken from the command line
main(new String[]{"bla", "blah"});
The main() method is defined by the java launcher:
The java command starts a Java application. It does this by starting the Java Runtime Environment (JRE), loading the specified class, and calling that class's main() method. The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration has the following form:
public static void main(String[] args)
That explain why you need it: It's required to start running a Java program.
And how it works: It's called by the launcher at startup.
public static void main (string[] args) is a main method which must be given an array of strings as arguments.
However, when I run a program, the main method automatically runs without me needing to explicitly call it with arguments.
Therefore, I have the following questions:
Does the type of argument of a main method matter?
Are there situations in which one would explicitly call the main method with arguments? If so, what is an example of such a situation?
Does the type of argument of a main method matter?
Yes. The JVM uses public static main(String[] args) as the entry point of execution for general Java applications. In other words, this is where the JVM is going to hand off execution from its own internal loading and initialization routines to your own bytecode. Unless you are executing an application inside a container (eg. GlassFish) or framework (eg. JavaFX) you will need to have this entry point for your code. By convention it is public static main(String...).
Are there situations in which one would explicitly call the main
method with arguments? If so, what is an example of such a situation?
Arguments to main(...) come mainly from two places:
The Command line. When you start a Java application from the command line inside a shell or Windows cmd.exe, you can type in some additional data after the name of the JAR file to execute. These additional data are processed into an array of Strings that is passed to your main() method.
A configuration setting. Most IDE's allow you to specify command line parameters for a project. You can pass parameters to the entry point (when you build and run your project) in this setting just as you would on the command line.
As mentioned by Dave, your own code would not invoke the main(...) method itself. It really is intended to just be the entry point.
Of course; the JVM only calls main(String[]) automatically. It's specifically for taking string args from the command line.
It's just another method: while it's almost always used as an entry point, there's no technical reason you can't use it like any other static method. I wouldn't, because it's atypical and non-communicative.
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
The main method accepts a single argument: an array of elements of type String.
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application.`
You can read some more here and the main Java documentation, which is very practical, is here.
Also for your second question, yeah you can do it but I don't suggest it.
This question already has answers here:
Why is main() in java void?
(4 answers)
Closed 7 years ago.
Although the return type is not a part of a method's signature, JVM looks for exact declaration as
public static void main(String[] args)
My assumption is that since method signature does not have "return type" included, I must be
allowed to change the return type.
But if I change it to public static int main(String[] args) and return a value lets say 0, JVM is not able to execute the program and exits with an error
Error: Main method must return a value of type void in class TestData, please
define the main method as:
public static void main(String[] args)
Why do Java Specifications want the main method to be void only?
Why is this restriction, when return type is not a part of method signature?
This question is different than Why is main() in java void? : this question is closed as it is opinion based, while I am looking for the code places/ processes from where JVM is invoking this method, and what are the limitations which are forcing them to keep this method as void. What are the design decisions they have taken (and the reasoning behind), and where is it documented.
I am looking for facts, so as to know the reason why is it done so.
Please don't mark it duplicate without going through the details of the question.
PS: exit, is another thing. I am more concerned about entry of the program. Also, the returned value might not be to the use of JVM, restricting it to void limits extensibility.
So far what I have learnt from this question is : Java specifications have explicitly fixed return type to avoid confusion to migrating programmers (C/CPP) who may expect this value to return to OS, but since JVM is in-between this value will never be returned to OS. For this special purpose (returning value to OS) they have provided System.exit() method.
For all those who are suggesting that return type is part of signature-- Just try to define both of the following methods in a class
public static void main(String[] a){
}
public static String main(String[] a){
}
You will get a compilation error, because signature of both of these methods is same.
The main is void is specified in JLS 12.1.4 Invoke Test.main:
The method main must be declared public, static, and void.
Sometimes the answer to a why? is because the specification says so (aka Quod Ego Dixit, or Because I Say So (Terry Pratchett)). Sometimes the decisions of a language designer are not available and the only thing we can do is guess. This is also the reason the obvious duplicate (Why is main() in java void?) is closed as primarily opinion-based.
Now as the - to me - obvious reason: JLS 12.8 Program Exit says:
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
This means that the end of the main method does not necessarily mean the end of the program. A return code from a main method has a well-known meaning in languages like C: it is the process exit code. This meaning doesn't apply when the main method may exit long before the process itself ends.
Most non-trivial Java applications have - usually- a short-lived main method that kicks off one or more long-living non-daemon threads. Allowing a return code from a Java main method could imply a meaning that is not actually there: that the return value is the process exit code. So explicitly specifying that main must have a void return type is good thing: it reduces confusion or assigning meaning that isn't there.
The main method may not be an exit point after all. Due to multi-threading it may happen that when the main returns there's still another thread on the pitch keeping the program alive. An exit code makes no sense in this case.
Why not void?
If you wish to return some status to OS you can use any of exiting methods.Most common one being System.exit(int status) .
If your main finishes before the other threads, a return value won't matter.
This is in contrast with c/c++ which do not supported multi-threading that time.
Like a swing application may still work on EDT after finishing main.
And if you are still considering the "entry" point: but the return type always talks about the exit.
So it's simply void as we have status signallers to return a value or no return in other case.
Still, there is no other point because it was designed in this way.Another developer with different thoughts might throw another idea to solve same situation.Depends.
As stated in
http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.8
12.8. Program Exit
A program terminates all its activity and exits when one of two things
happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System,
and the exit operation is not forbidden by the security manager.
the program exits, if all running threads are deamon. So if you have a non deamon thread, the main method might return before the program ends.
The lifetime of your program can extend the lifetime of the main method and the return number might be decided later in the program.
I think this is why they use System.exit() as return point.
You can't look at below from Java Docs, for your main method to serve as exit point you need to have the method void. or you have an option to call system.exit() explicitly at the end of you main.
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
As per my knowledge,
The reason for the main method having void as return type is that, once the main method finishes its execution, it doesn't mean that the entire program finished. It may have some threads initiated and running behind the scene. Even if the main thread is dead, still there is a chance of child threads to be running. In this case the return type of main doesn't make much sense.
And JVM will monitor the program completion status to deallocate the memory, Its not necessary to return something to JVM that states the program is finished. In C-language we are directly communicating with O.S. so, there is an option to return int value to O.S. that states the execution is done and start deallocating the memory. But here in java, JVM will communicate with O.S. but not the program, So we no need to return anything from main.
Hope this clears your doubt.
If you ask JVM to run a class, java runtime will look for exactly that signature in your class public static void main(String[] args)
That is your contract with the JVM, if not, it will not execute.
If you want an int code back, use System.exit
A console program returns an int return code, and thus in a traditional C program an int main(int argc, char** argv) seems logical.
In Java the exception was introduced as a new control flow mechanism, and also multi-threading was simulated or now implemented. Exit could be done everywhere with System.exit(int returnCode).
This means that the call to main is embedded in a piece of code, and cleanest (minimalistic, less cases, no magic of return 0) is to a default of returning 0, except by System.exit.
Mind, java was intended to strongly "improve" upon C and especially C++. Like having Strings and char that use full Unicode as opposed to byte.
Java has been designed as a Platform independent language. So if it's main() method returns a value (like 0 or 1 or anything), it can be interpreted or understood differently by different platform. So, unlike C and Cpp it's main() method can't return a value.
The main reason is that in common use cases particularly in multi-threading and GUI apps you don't prefer to have a return value in main. But if really you have such a use case, you can use exit method. This is the reason that you are looking for.
What is main method in Java?
Main method in Java is entry point for any core Java program. Remember we are not talking about Servlet, MIDlet or any other container managed Java program where life cycle methods are provided to control the execution. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.
Signature of main method in Java
Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not run. Here is the exact signature of main method:
public static void main(String args[])
This signature is classic signature and there from start of Java but with introduction of variable argument or varargs in Java5 you can also declare main method in Java using varargs syntax as shown in below example:
public static void main(String... args)
Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main method.
Why main method is static in Java
why main method is public static void in JavaNow come to the main point "Why main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:
Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
Since C and C++ also has similar main method which serves as entry point for program execution, following that convention will only help Java.
If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
Why main mehtod is public in Java
Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public in
Java, JVM can easily access and execute it.
Why main method is void in Java
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.
Summary:
Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
JVM throws NoSuchMethodException:main if it doesn't find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.
Main method is entry point for any Core Java program. Execution starts from main method.
4. Main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.
When you see "Exception in Thread main” e.g.
Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.
You can declare main method using varargs syntax from Java 1.5 onwards e.g.
public static void main(String... args)
Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.
Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified
above.
You can use throws clause in signature of main method and can throw any checked or unchecked Exception.
Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.
I hope this has answered your question about the main method :)
Update in response to:
One small problem with your answer: Return type is not a part of
method signature.. hence, JVM must not throw the exception
"NoSuchMethodException:main" if the return type is different.
it doesn't return "NoSuchMethodException:main" if the return type is different and the return type is a part of the method signature. Take a look at this screenshot:
We can say, main method as class initilization method, since it satisfies one of the class initilization criterion; Please refer http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4, 12.4.1 section--
T is a class and a static method declared by T is invoked.
Now, as per JVM specification, return instruction is used to return from methods declared to be void, instance initialization methods, and class or interface initialization methods.
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11.8
Please see details about return instruction here: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.10.1.9.return
I just started studying Java. And the main function of the program always resides in a class.
public class t{
public static void main(String[] args){
// do stuff
}
}
I have studied C++, and in there the main function doesn't need to be in a class. Why in Java we have to do that?
Why can't the main function exist in Java without a class, like it does in C++?
Probably for the same reason you put question marks at the end of a question: that's just how they decided it's done.
The main method is the result of a convention that says "this is how the entry point's method signature should look" which doesn't exempt it from language semantics.
Java does not support methods outside of classes/interfaces and as such it has to be contained in one.
The "every method in Java must be in a class because the spec says so" answer is only part of the story. By having main() inside a class it is possible to have multiple entry points within a project. i.e. multiple classes with main() methods. This allows you to select a different main class at runtime rather than compile time. e.g.
java -cp program.jar com.example.Class1
or then if you want to run a different main from the same jar
java -cp program.jar com.example.Class2
Because that is how the language was designed. The JVM first loads the class containing the main function and then calls the main() method. Without loading the class, main() cannot be called, i.e, main() doesn't exist without its enclosing class.
All methods must reside in a class in Java.
main is a method.
Therefore, main must reside in a class.
Furthermore, a class is not just a blueprint of an object. It is by itself a chunk of code that does something. One of the things it does is providing the entry point of the application by containing a main method.
Because everything is inside a class in Java. Java code consists only of classes. They may be nested in themselves or in a packagehierarchy, but nothing is allowed to appear outside of a class.
The only exceptions are the package and import statements.
since java is oop language , u cant do anything unless u create a class. this makes java object oriented language. and java was designed like that to first to load the public class and call main method
Let's consider that following is allowed in java
void main (){
f1();
f2();
}
int f1(){
f2();
return 1;
}
int f2(){
return 3;
}
since there are no prototypes in java how would main call f1 or f2 or how would f1 call f2?
i Think that this is one of the reasons
So I just tried excluding String[] args from the main method
It compiled alright !
But JVM is showing an exception
Why did it compile when String[] args HAS to be included every time ?
What is going on here ? Why won't it show a compilation error ?
typing this made me think that may be compiler did not see it as THE main method ..is that so ?
If that is the case..why not ? I mean isn't there supposed to be just one main method that MUST have String[] args as the argument ?
typing this made me think that may be
compiler did not see it as THE main
method ..is that so ?
Correct. There is no compile error because you're perfectly free to have all kinds of methods named main. But when you start the JVM and give it a "main class", then it will look for a method static public void main(String[]) in that class, and if it does not find such a method, it aborts with an exception.
This allows you to have multiple main methods in your program and is really the only thing that makes sense if you think about it: Applications can be composed from classes and JAR files from lots of different sources, written by different people at different times, so in many cases you can't really have a single, designated "main class" right from the start.
The JVM is looking for a very special main method to run. Only the signature
public static void main( String[] args )
is found. All other methods with name main are just "normal" methods.
Not every class has to have a public static void main(String[] args) method, only the one you want to run from the JVM. The result is that your class will compile with no error if it finds public static void main() but will throw an exception if you try and run it with the JVM because it can not find the entry point of the program.
Bottom line the entry point of your program must be public static void main(String[] args) which must be located in at least one of your .java files.
Note you can have multiple public static void main(String[] args) methods in your code (one per class) the advantage is you can use these to test and debug your classes individually.
To try to answer "why is it legal to compile without a proper main method" it's because not every java project is a stand alone application that can be run. Some are just libraries, where other programs will include them as jar files and use their code, but they don't "run" themselves. Others may be web applications, where they are deployed onto a web server that has already been started, only the server itself actually has a proper "main" method. The web application project is opened up and executed by it.
The compiler didn't really know at compile time that you were intending to try to run your code as a stand along application.
Java supports method overloading. This means you can have several methods with the same name, but different arguments.
Having said that, when you run java ClassName, Java looks in ClassName.class for a method with the signature public static void main (String[]) (it doesn't care what the String[] variable is named) and runs it. If it doesn't find one, Java will bomb out with the following exception:
Exception in thread "main"
java.lang.NoSuchMethodError: main
You are correct. The runtime is looking for a main method that takes a string array as a parameter, and isn't finding it.
The fact that you have a main method that doesn't take a string array is irrelevant. just like any other method, you can create multiple versions of main() that take different parameters - the runtime will just ignore them.
Isn't that overloading? It's fully legal to define a method
static void main() {
}
It's just not the entry point the JVM will be looking for.
Overloading is the ability to have multiple methods with the same name but different arguments. The compiler in fact creates a name based on the method name and the arguments.
So a main(String[]) would be called, to the compiler, something like main_String_arr, and main() would be called something like main.
You can have many methods named main, but only one can be THE main one - entry point to the program. It is the one with String[] args.
It's still a valid method. For example, you could have a static method called "main" with an int parameter if you wanted:
public static void main(int foo){}
The compiler doesn't complain because it's a valid method! It's just that, in order to run a Java program, Java looks for a static method called "main" with a single String array argument.
Yes..
The Java compiler will look for the same method signature to consider it a main
Writing any function that has the same name but another parameters will result in overloading functions..
Overloaded functions are not the same..!!
The case in C# is somehow different..
At last, you must make sure that your main is like that:
public static void main(String[] args)
You can use the compiler to compile part of an application: e.g. to make a jar file which you will call from another part of the app; or an applet that is started in a different way. Therefore the compiler cannot complain about the lack of a main(String[]) method. But trying to run the results of such a compile.
When you try to run the results of such a compile java is always looking for a specific main(String[]); if it can't find it it will throw a runtime exception. The main used to start an app must have exactly that signature.
Here's a quote from Java Tutorials/Getting Started:
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
So to be precise, the main method is defined by Java as an application entry point. Not everything is an application, and not every main method is an application entry point. Applets, for example, don't need a main, because it's started with a different mechanism.
Note also that since the introduction of varargs, you can actually declare your application entry point as follows:
public static void main(String... args)
This works because underneath the syntactic sugar, varargs in Java is implemented as arrays.
See also
Java Tutorials/Getting Started/Hello World
Java Tutorials/Command Line Arguments
Java Language Guide/Varargs
Related questions
Why is the Java main method static?
is possible to overload a main method?
Why main() in java is void?
Why do applets not need a main()?
Entry point for Java applications: main(), init(), or run()?
Important points:
Following is the signature of the main method:
public static void main(String[] args)
main method can be overloaded.
Multiple classes can contain the main method inside a single compilation unit (and so all of them will be called executable classes)
The class containing the main method may or may not be public.
By mistake, if you were to omit the static keyword (or the signature differs in any way), compilation would be done but a runtime error will occur.
From my blog:
Java: Important points about the main method