Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the main function in Java reside in a class?

Tags:

java

class

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++?

like image 908
ooodddbbb Avatar asked Feb 16 '15 13:02

ooodddbbb


People also ask

What does the main function reside in Java?

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.

Should main be inside a class in Java?

The main() method must be called from a static method only inside the same class.

Why is main function public in Java?

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.

Why do we write main method in class?

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.


2 Answers

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.

like image 173
Jeroen Vannevel Avatar answered Nov 07 '22 20:11

Jeroen Vannevel


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
like image 37
bhspencer Avatar answered Nov 07 '22 21:11

bhspencer