Can we execute a program without main function in Java?

My answer to Can we execute a program without main function in Java?

Answer by Vaibhav Kashyap:

What you're trying to do was possible till Java 6 using 'Static Initialization Block' because as soon as your class is loaded you get the result that's because static blocks are executed even before the main method. Follow the code below:-

import java.util.logging.Level;
import java.util.logging.Logger;

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.

 * @author vaibhav.kashyap
public class RunByStatic {
        try {
            System.out.println(" The Result is HO HO HO : "+add(3, 5));
        } catch (Exception ex) {
            Logger.getLogger(RunByStatic.class.getName()).log(Level.SEVERE, null, ex);
    public static int add(int a, int b) throws Exception{
        return a+b;   

Above code if you try to execute using jdk 1.6 or below could have resulted in '8' however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main.

In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).

Can we execute a program without main function in Java?


Currently Working as Game Developer at Gaussian Networks Private Limited , ( ). Did B.Tech in computer science Engineering from G.G.S.I.P University , new delhi. Using Java , ActionScript 3.0 and PHP for development. I am a programmer who loves to adapt new platforms for coding. Reading techs & specs of gadgets is my hobby as i am a 24x7 active web crawler. I consider learning as a best helping aid to yourself as well as for others because it's the best means for diversifying your knowledge.

Posted in J2SE

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: