File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Main method important in java? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Main method important in java?" Watch "Main method important in java?" New topic
Author

Main method important in java?

Dhivya rajagopal
Ranch Hand

Joined: Dec 15, 2010
Posts: 42
hello, I studied that java cant run without main method, but the following produce the output
class hello
{
static
{
System.out.println("java");
}
}
How it is possible? Can you please tell about static also
Thank you in advance
Zandis Murāns
Ranch Hand

Joined: Aug 18, 2009
Posts: 174

This is not possible at all. You'r main method is declared elsewhere and you're not seeing it, but still this main method exists in other class - that's my guess.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11402
    
  16

When I run you code, i get the following:

C:\slop>java hello
java
Exception in thread "main" java.lang.NoSuchMethodError: main

So it does print out java, but I wouldn't say it really 'worked'.

Static blocks can and will run before various other things, but its almost always a bad idea to use them. this is nothing more than a 'trick' or a 'hack', IMHO.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
hopefully you have tried a java hello from the command prompt. The first step is that the class gets loaded into JVM. So you see the "java" printed on the cmd prompt. And then you should see a error?

Alternatively if any other class like Zandis pointed out tries to initialize this class (loading first time by the JVM!) you will get the "java" printed on the console.

Try running below code... the static block will be executed only once...

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
John Jai wrote: And then you should see a error?

Same one Fred shown
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

Zandis Murāns wrote:This is not possible at all.

Well, as you can see in the examples in this post, it is possible.

For some reason people ask this question now and then on the forums here: "how can I write a program that runs without a main() method", etc. I wonder why so many people are asking this (is there someone or some company who asks this to people as a trick question for job interviews?).

Anyway, it's an interesting but practically useless trick, I suggest you forget it immediately and never use it in any real program.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Main method important in java?