3

The following program will print Hello world when compiled with JDK 1.6 or lower versions of JDK.

    public class A
    {
      static
      {
        System.out.println("Hello world");
        System.exit(0);
      }
    }

But JDK 1.7 or higher versions will generate a runtime error as follows when the above program is compiled.

    Error: Main method not found in class A, please define the main method as:
       public static void main(String[] args)
    or a JavaFX application class must extend javafx.application.Application

I would like to know if there is some way to compile and run a program without main() successfully in Java using JDK 1.7 or higher.

Thanks in advance.

1 Answers1

9

No. public static void main(String[] args) is the main entry for all Java applications. There are frameworks that makes you believe there's no need of this method, like a unit test executed by JUnit, but the fact is that the framework has a main method defined somewhere inside it, does the necessary calls for you and ends calling your code.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Your answer helped me to gain knowledge. But I have to somehow implement a program without main() since I am asked to do so. –  May 19 '14 at 17:57
  • @AbyWang I wonder which kind of boss do you have to make you do this. Anyway, you can create a web application, where the `main` method is in the application server, your application won't need a `main` method. – Luiggi Mendoza May 19 '14 at 17:58
  • It was an assignment assigned to us during our training in Java. We implemented it using `static` blocks in Java since the version we were using there was jdk 1.6. But the same program was not working when I tried as home. Hence I posted this question. –  May 19 '14 at 18:01
  • 8
    Then you have the worst instructor all time and should get your money back – tomsontom May 19 '14 at 19:54
  • OK, nitpicking here, but it doesn't it necessarily have to be args – Gonen I Jan 08 '18 at 21:33
  • @user889742 it's a variable, so the name could be whatever you want. But `args` is the standard name for the arguments of an application (also the name implies it). – Luiggi Mendoza Jan 08 '18 at 21:34
  • I encountered this error recently as my project was create and compiled in jdk6 and I imported it in jdk8 environment. Removing the 1.6 library and adding 1.8 library fixed it for me in a flash. – Ajay Kumar Feb 07 '19 at 19:27