This question already has answers here:
Can I invoke a java method other than main(String[]) from the command line?
(8 answers)
Closed 2 years ago.
We know that JVM looks for main() method during class execution. Can we customize JVM to execute our own custom function instead of main method by default?
if yes, how do we do it?
You can do this by implementing a native custom launcher as described here:
http://www2.sys-con.com/itsg/virtualcd/java/archives/0709/chamberlain/index.html
But frankly, it is not worth the effort if you simply want to use a different convention for the entry point. A simpler approach is to write a "proxy" entry point class with a conventional main method, have that find / load / call your "real" entry point.
On the other hand, if your goal is to execute some code before the main method gets called, one trick is to put the code into a static initializer block in the entry point class. For example:
public class Entry {
static {
System.out.println("Hello world");
}
public static void main(String[] args) {
// ...
}
}
will print "Hello world" before the main method is called.
Speculation! It might also be possible identify the hidden Java bootstrapping class that finds / loads / calls the normal entrypoint class. Then you could replace it by adding a modified version to the bootstrap classpath. However, you will be straying into dangerous territory. Interference with hidden mechanisms is liable to end badly if you get it wrong.
No. The main(String[]) method is the Java entry point. You can package your application as a jar then you can set the Main-Class and run it like java -jar myapp.jar. See also Setting an Application's Entry Point. That being said, any static initialization blocks will run before main. But you get an exception if the class specified doesn't have a main method. The only other exceptions I can think of are Servlets and (the almost dead) Applets.
This question already has answers here:
Where will i put "Public static void main(String[] args)"?
(4 answers)
Closed 6 years ago.
I'm using I believe the latest version of Java and Eclipse.
Her instructions say: "Create a new class. A field is a String message "Taking COMP 110". A method printing is used to print a message string. "This method is from an object." Then it says "give an explanation of what is happening. Why the same result?""
And the example she gave is:
public class myOwnObject {
String anylegalname = "taking COMP 110";
public void printing(){
System.out.println(anylegalname);
}
}
But I tried this and... it doesn't work. Eclipse tells me it needs public static void main(String [] args)... what gives?
One class in your .java file must have a public static void main(String[] args).
This is the entry point for your application.
So you wrote a class, but you would need to add the above and instantiate an instance of your class inside your main.
Here's a tutorial that explains it a bit more:
http://docs.oracle.com/javase/tutorial/getStarted/application/index.html
Eclipse tells me it needs public static void main(String [] args)... what gives?
You're trying to run the class as the main class of a program, the Eclipse equivalent of the standard java myOwnObject command-line.
When you do that, the main class must have a static main method with the signature Eclipse is showing you, because that's the entry point of the program.
Only classes you want to run as the main class need this. So code that's run a different way (by a web server, by some other kind of container) doesn't need a main. Only the main class of a standalone program run via the java tool (or equivalent tool integrated into your IDE).
Your professor should have explained what main was for fairly early on. You should probably read some basic Java tutorials if she didn't, rather than relying on her.
She should also have told you that overwhelmingly, the convention in Java is for a class name to start with an uppercase character. So MyOwnObject (or better, MyOwnClass) rather than myOwnObject.
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