Can You Run Java Program Without a Main Method? [Interview Question Answer]

Hello guys, the first thing Java programmers learn is that they need a main method to run, but when they go to any Interview or college viva and ask can run a Java program without a main method, they are surprised like hell. Well, there are actually different types of execution models available in Java; for example, Applets, which run on the browser don't have the main method. Instead, they have life-cycle methods like init(), start() and stop(), which controls their execution. Since Applet is a Java program, you can answer this question is Yes. Similarly, we have Servlet, which runs in a Servlet container, comes as bundled in a web server like Tomcat, or Jetty.

The Servlet also works on callback mechanism, it has methods like init(), service(), and destroy(). Container calls init() if Servlet is a first-time loaded into memory, calls service() if there is a request to process, and calls destroy() before removing it from memory.

Since Servlet is also a Java program, we can say that it runs without the main method. The third one in this category is MIDlet, which runs on mobile devices like Nokia, Samsung, and others. MIDlet has life-cycle methods like startApp(), pauseApp() and destroyApp(), to start, pause and shut-down mobile applications.

Ironically J2ME has an app in its core method, but it was made popular by Android and iPhone. Since MIDlets are also Java programs, you can say they run without the main method.

Now, if the Interviewer persists with something like this, Can you run a Java program without the main method in Core Java, not on the managed environment like the case of Applet, Servlet, and MIDlet. The answer is NO, Why? I will explain that in the next paragraph.

By the way, if you are new to the Java world and want to learn Java in-depth, I suggest you check out these free Java courses for beginners and experienced. This contains several free courses to learn key topics like core Java, Multithreading, collections, socket programming, and more. 




Java program without the Main method

Many Java programmer gives you answer that they can run a Java program without a main method by writing code in static initializer block, which is half true. Yes, code written in static initializer block is executed before calling the main method, but you won't be able to run a class by using Java command, or Eclipse, or anything else, until it got public static void main(String args[]) method on it.

If you try to run such programs, you will get the following error :

Error: Main method not found in class JavaAppWithoutMain, please define the main
 method as public static void main(String[] args)

You can not run a Java program without main mehtod


Though you can run a Java program with an empty Main method, in which case only code executed will be from the static initializer block. Following is a simple Java program with some code written on a static initializer block, including a print statement, variable initialization, and starting a thread.

As soon as you remove the main method, it will compile fine but will throw the above error when you try to run this program from the command line.

By the way, this is one of the many questions related to the main method in Java; you can see other questions for your interview preparation then I suggest you check out this Java Interview Courses, which contains important topics and more than 200+ Interview Questions and Answers for beginners and sufficient to crack any Java interview.


/**
 * Java application to demonstrate whether you can run a program without a main method
 * or not.
 * @author http://java67.blogspot.com
 */
public class JavaAppWithoutMain {

    static {
        System.out.println("HelloWorld, Java progarm without main method");
        int x = 20; // Can initialize static variables
        System.out.println("Variable x : " + x);

        Thread t = new Thread() {
            @Override
            public void run() {
                System.out.println("Started thread from static initializer block");
    System.out.println("Thread Finished");
            }
        };
        t.start();
    }

    public static void main(String args[]) {
          // Empty main method
    }

}

Here is how the output looks like when you run this program from the command prompt with an empty main method.

Java program without main method



That's all about whether you can run a Java program without the main method in Java or not. In short, Yes, you can run a Java program without a main method in a managed environment like Applet, Servlet, and MIDlet, which runs under control of browser, server, and mobile device, but can't run a core Java program without public static void main(string args[]){} method. JVM will not allow you to execute those methods.


Other Programming Articles You May Like to Explore

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are new to Object-Oriented Programming and looking for some free courses to learn Object-Oriented Programming then you can also see this list of my favorite best courses to learn Java online for beginners.

14 comments:

  1. abstract class Test extends javafx.application.Application
    {

    static
    {
    System.out.println("hello");
    System.exit(0);
    }

    }





    //this code is new feature in jdk 8 version.without writing main method we can get the output in jdk8.in jdk 7 or older,application class is not there so we will get error.and we can also get the output by writing normal code of static block in jdk6 or older like



    class Test
    {

    static
    {
    System.out.println("hello");
    System.exit(0);
    }

    }



    it is impossible to print output in jdk 7.but if u will write main method without implementation that time u can print the content of static block in jdk 7 also.
    so just remember in jdk6 or older it is possible,in jdk 7 it is not possible and in jdk 8 it is possible by extending our class by application class as shown above.
    also applets,servlets,MIDlets(for mobile app) is having there own life cycle so that they can also execute without main.u can also create ur personal JVM launcher in which u can define anything u want that ur personal jvm willl not search the main method...

    ReplyDelete
    Replies
    1. package com.test;

      public class Test {
      static {
      System.out.println("HOLAAAA");
      System.exit(1);
      }

      }

      //coco
      //Command line :)
      //java -Djava.security.manager=com.test.Test

      Delete
  2. What are the use cases we can use it?

    ReplyDelete
  3. Well, an api or library does not need to have a main method, if that case counts?

    ReplyDelete
  4. In Java, Up to Java 6 it was possible to do this using the Static Initialization Block. For solve the problem to a execute java program without having main method.
    For example we have writing the following code using static block:


    public class CheckWithoutMain{
    static{
    System.out.println("static block is Executed");
    System.exit(0);
    }
    }

    To read more in details please visit this articles-----http://www.mindstick.com/Articles/11934/how-to-execute-a-java-program-without-having-a-main-method

    ReplyDelete
  5. Yes, we can write java program without main. until java6, it is possible execute without main because jvm will load main class bytecode to the memory without checking main method, jvm will execute staticblock & jvm will display required msg.
    incase of java7, jvm will search for main method and then jvm load bytecode to memory for execution...if not found then it rises an execption like "main method not found".
    This(execution of writing prog without main method) is possible in servlets also......








    class Demo{
    static{
    System.out.println("static block is Executed");
    System.exit(0);
    }
    }

    ReplyDelete
  6. you can also:
    - convert java class into dll using Excelsior Jet, load it and call any java method, not only main()
    - load JVM as DLL, then using JNI, load any java class and call any its method

    ReplyDelete
  7. write a program in java to enter a number and check whether number is a palindrone or not

    ReplyDelete
    Replies
    1. Hello Anonymous, I have already written one, you can check it here
      http://www.java67.com/2012/09/palindrome-java-program-to-check-number.html

      Delete
    2. package com.st.ems.corejava;

      import java.util.Scanner;

      public class Pallindrome {

      public static void main(String[] args) {

      int n, b, sum = 0, rem;

      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a Number=");
      n = sc.nextInt();
      b = n;

      while (n > 0) {
      rem = n % 10;
      sum = sum * 10 + rem;
      n = n / 10;
      }
      if (b == sum)
      System.out.println("Number is Pallindrome");
      else
      System.out.println("Number is not Pallindrome");

      }

      }

      Delete
  8. {

    static
    {
    System.out.println("hello");
    System.exit(0);
    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.