Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java requires the main() method to be static. C and C++ however don't require such. Why?

Tags:

java

Let's look at the method signature of main() in C, C++ and Java without paying much attention to it.

C and C++ take the syntax of the main() function something like the one shown below.

int main(void)
{
     //Elegant code goes here.

     return(0); 
} 

or it can simply be declared void as shown below.

void main(void)
{

     //Elegant code goes here.

} 

The main() function in C and C++ can optionally takes two command-line arguments, if needed.


The signature of the main() method in Java however, something like this.

public static void main(String []args)
{

    //Elegant Java code goes here.
}

Java requires the main() method to be static simply because it was clearly mentioned that it is the first method to be invoked when no objects were created hence, it must be static. The same thing is also applicable to C and C++. There also the main() function is the first function to be invoked still they don't require the main() function to be static. Why? Why did the Java designers take somewhat different view to implement the main() method in Java?

like image 581
Lion Avatar asked Dec 05 '25 06:12

Lion


1 Answers

C has no objects and all methods are static; in C++ one has to declare methods as virtual for them to be not static.

like image 76
Jilles van Gurp Avatar answered Dec 07 '25 21:12

Jilles van Gurp