Skip to content
Related Articles

Related Articles

Improve Article
Java Program to Print any Statement without Using the Main Method
  • Last Updated : 17 Nov, 2020

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :