I am getting error while running Java program without main(),but I used only static block to test whether the program will execute or not without main().Is there any other way to execute Java program without main().
Asked
Active
Viewed 67 times
-1
-
1Show your code and show the exact error message that you get. – Jesper Jul 19 '15 at 10:58
3 Answers
3
Put System.exit(0) just before the end of the static block. You need this in order to terminated the program just before it will start searching for main method.
This question is already answered - link

Community
- 1
- 1

Teodor Simchev
- 121
- 1
- 4
0
Yes, you can use static
initializer block , like this :-
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Outputs :-
Hello, World!
Exception in thread "main" java.lang.NoSuchMethodError: main
You can avoid the NoSuchmethodError
by simply calling System.exit(0)
immediately after printing the message like :-
static {
System.out.println("Hello, World!");
System.exit(0);
}

AnkeyNigam
- 2,810
- 4
- 15
- 23
0
Please mention which JDK you are using. If you are using JDK 7 then it will not allow you to run without main();
If you are using JDK 6 and Below you can do same without error as follows:
public class Hello {
static {
System.out.println("Hello, World!");
System.exit(0);
}
}

VIjay J
- 736
- 7
- 14