Trick : Java program with out main
- 4 October, 2009 //
- Programming //
- Tags : java porgram, java porgram tips.java trick, java without main, simple java program, without main
- 6 Comments
Writing a java program with out main thread.
Tricky way to compile a java program with out any main
class sample
{
static
{
System.out.println("Hello Word !!");
}
}
Well, okay, but it terminates with an exception.
69 $ cat > sample.java
class sample
{
static
{
System.out.println(“Hello Word !!”);
}
}
70 $ javac sample.java
71 $ java sample
Hello Word !!
Exception in thread “main” java.lang.NoSuchMethodError: main
72 $
So you get your output, and then it crashes… good one
Hello Word !!
java.lang.NoSuchMethodError: main
Exception in thread “main”
This is not a trick, it’s just bad programming, that any IDE would pick up automatically by the way.
This makes no sense. You don’t need a main method to compile a java class.
“Writing a java program with out main thread.”
If there wouldn’t be a thread, there wouldn’t be *any* execution of code
“Tricky way to compile a java program with out any main ”
All my classes compile without a main, but they won’t run without it
Btw: I don’t see any sense here… and if try to run a mulithreaded Server like this and you will fail.
The naming for the class is wrong. It should be Sample (upper case S).
Hi,
if you dont want to exit with an exception then write the program in this way……
class sample
{
static
{
System.out.println(“Hello Word !!”);
System.exit(0);
}
}
if you use System.exit(0); then it will not go into the main method and there cant be any exception.