• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Running code without main()....

 
Ashwin Sharma
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all....

Suppose you create a file name Test.java and then add following piece of code to it-

Public Test{
static{
System.out.println("runned without main()");
System.exit(0);
}
}
And then compile it and run the output will be as expected.
So my question is can you replace main and use the above method(offcourse in some cases as it don't takes arguments). Will there be a performance hit or some other issues....
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

So my question is can you replace main and use the above method(offcourse in some cases as it don't takes arguments)

What happened when you tried it?
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did that run?
Actually jvm looks for a method which has the signature of main(String [] a)
and then calls that marking the start of the program..I do not think your class should run.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it runs. The static initializer is executed while the class is loaded. At the end of the initializer, System.exit() is called, so the program exits. If you hadn't called System.exit(), of course, java.exe would next have tried to find the main() method of the loaded class, failed to find it, and exited with a diagnostic.

Is this a serious question about performance? That's kind of like asking whether flushing the toilet is going to make the oceans overflow. One tiny reflective method call is nothing compared to the time it takes to start and stop the JVM. This has no measurable impact on performance whatsoever.
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static block will execute your program as if you started it with a main() method (no arguments though).
It will not improve performance and will definitely make it a lot harder to understand (what do you search first for if you try to find the entry point of a program ?)


That's kind of like asking whether flushing the toilet is going to make the oceans overflow.


Will it ?

:-)
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see two implications:

- you can't pass any command line arguments to the program, and

- you could get your initialization wrong (static fields that are declared after the static initializer will get initialized when the program *finishes* :eek
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic