Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why does java compiles successfully ,but doesnot run when theres not any main method  RSS feed

 
Vishal Hegde
Ranch Hand
Posts: 1078
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does it compiles and shows a runtime exception when theres no main method???
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why shouldn't it compile? Code doesn't have to have a main method to compile. But you must invoke the class with the main method to start your application off, so you will suffer an Exception.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If source files would not compile without a main method, then every single class will become an application on its own (because you can execute it). Now what would application "java.util.ArrayList" need to do according to you? Or application "java.lang.String"?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12564
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a large application might have thousands of class files, all of which must be compiled. Only one of them needs a main() method. So writing a class file without a main() method is perfectly valid. I believe the Math class doesn't have one.

It won't run because when you say "java MyClass", you're implicitly telling the JVM to run the main() method in MyClass - so if there isn't one, it's gonna complain.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't remember seeing a main method in the standard Sun Java API. I can't find a "main" in the API index under "m".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!