• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does a non-static main method throw an error  RSS feed

 
krishnadhar Mellacheruvu
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
was trying to understand the signature of main method.

public static void main(String[] args)
{

}

the above code compiles without an error.

now when the change i.e. make the main method non-static

public void main(String[] args)
{

}

the above code throws an error..

now i understand that static keyword binds the method to the class and the static method needs to be accessed in a static way i.e. with the help of class name

i.e for example zoo.main();

Y does a non-static main method throw error and y cannot main method be non-static...
 
Junilu Lacar
Sheriff
Posts: 11481
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please be more specific. What is the exact error message? Is it a compile-time error or run-time error?
 
krishnadhar Mellacheruvu
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI

its a runtime error...

Error: could not find or load main class static..
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because java command looks for a method with signature public static void main(String[] args).
If it can't find one it prints the error message.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The creators of Java decided that that was the signature that was needed to start a Java program. They could have decided to allow non-static main methods if they wanted, but they didn't.

We can only speculate why that is, but it's probably because they were trying to make it as similar to the entry point of a C/C++ program as possible (to keep it familiar). These languages have a global method called main(). Static methods are the closest you get to global methods in Java.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!