Open In App

Java Program to Print any Statement without Using the Main Method

Last Updated : 17 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




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


Output

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads