Friday, January 23, 2026
HomeLanguagesJavaJava Program to Print any Statement without Using the Main Method

Java Program to Print any Statement without Using the Main Method

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

RELATED ARTICLES

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
119 POSTS0 COMMENTS
Nango Kala
6847 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6912 POSTS0 COMMENTS