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++?
static – Java's main method is static, which means no instances need to be created beforehand to invoke it. void – Some programming languages return a zero or 1 to indicate the main method has run successfully to complete. Java's main function is void, which means it does not return any value when it completes.
The main() method must be called from a static method only inside the same class.
Java main() method. public: It is an access specifier. We should use a public keyword before the main() method so that JVM can identify the execution point of the program. If we use private, protected, and default before the main() method, it will not be visible to JVM.
Reasons for defining main() method as static We create the main() method as static so that JVM can load the class into the main memory. The main() method is the entry point of each and every Java program. The main() method is required because the compiler starts executing a program from this entry point.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With