Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Main method important in java?

 
Dhivya rajagopal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 174
Java Java ME Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12127
30
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Jai wrote: And then you should see a error?

Same one Fred shown
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15288
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic