Can we print something on console without main method in java?

Yes, it was possible in older versions of Java to print output without explicitly writing a main() method by using static initialization blocks or applets. However, this approach is no longer practical or supported in modern Java applications. In current Java versions, the JVM requires a main() method (or the newer simplified entry point features introduced in recent Java versions) to start a standalone application.

Key Points: • In older Java versions, code could execute through static blocks before the main() method. • Prior to Java 7, a class containing only a static block could sometimes be executed successfully. • From Java 7 onward, the JVM requires a valid main() method for application execution. • Static blocks still execute during class loading, but they cannot replace the application's entry point. • In modern Java development, main() remains the standard starting point for program execution.

Example: In older Java versions, the following code could print output without defining a main() method.

Code Example:

class Demo {

    static {

        System.out.println("Hello World");
        
        System.exit(0);
    }
}

Output:

Hello World

Why Did It Work?

• The static block executes when the class is loaded. • System.exit(0) terminates the JVM before it searches for the main() method. • This behavior was accepted in older Java versions.

What Happens in Modern Java?

Without a main() method, the JVM reports an error such as:

Error: Main method not found in class Demo

Therefore, a valid entry point is required for standard Java applications.

Common Interview Perspective:

Older Java Versions: • Possible using static blocks

Modern Java Versions: • Not possible for standard applications without an entry point method

Interview Tip: A concise interview answer is:

"In older Java versions, output could be printed without a main() method by using a static block and terminating the JVM with System.exit(0). However, modern Java versions require a valid entry point, so a standalone application cannot normally run without a main() method."