• Register

The response to this query rest on on the version of java you are using. Earlier to JDK 7, the main function was not obligatory in a java program.

·         We could write our complete code below static block and it execute routinely.

·         The static block is initially run as soon as the class is loaded beforehand the main(); the function is called and consequently earlier the main() is called. main is typically stated as static method and therefore Java doesn’t want an obj to call the main method.

·         When we will provide the run command(i.e java Test1 in the below-stated program in notepad++), so compiler assumes Test1 is that class in which main() is there and meanwhile compiler load, the main() function, static blocks are prepared to get run. So here, it will run static chunk initially and then it will see no main() is there. Consequently it will give “exception”, as exception arises while running. Though, if we don’t need an exception, we can dismiss the program by using System.exit(0); command

Though, from JDK7 main function is compulsory. The compiler will confirm first, whether main() is existing or not. If your code doesn’t comprise the main function, then you will get an error “main function not discovered in the class”. It will spring an error (byte code confirmation error since in it’s byte chunk, main is not there) not an exception because the program has not executed up till now.

Reminder:- Though, both the programs will become compiled since for compilation we don’t want main() function.

Is main function obligatory in Java?

// prior to JDK 7 
public class Test1  
{ 
    // static block 
    static
    { 
        System.out.println("Hello User1"); 
    } 
} 

 

2,760 points
7 4