Open In App
Related Articles

Java Program to Print any Statement without Using the Main Method

Improve Article
Save Article
Like Article

As we know that the static block executes before the main method, hence we can place the statement that we want to execute in the static block, But in case of JDK7, and the above versions of the JDK, the code would not execute as compiler firstly looks for the main method before any other thing. Also, it depends on the IDE being used to run the program, ie the program might get executed successfully on some IDE, and might not on some IDE’s. Also, we can abnormally exit our program in the static block so that the JVM will not check the main method, but as discussed it depends on IDE, whether the program will run or not.

Example: Below is the code implementation of the above approach.


// Java Program printing the statement without using main
// method.
class PrintWithoutMain {
    // static block
        // prints "Hello World!!" to the console
        System.out.println("Hello World!!");
        // exit from the program


Hello World!!

The above code does not compile before and on JDK7. Also, one might get the error like below if run the above code on some IDE like Intellij or Netbeans or console. 

Error when main is not used

Last Updated : 17 Nov, 2020
Like Article
Save Article
Similar Reads
Related Tutorials