How to print in Java without main() method

💻 Did you know you can print output in Java without a main() method? Here’s how 👇 class WithoutMain { static int variable = 10; static { System.out.println(variable); System.exit(0); } } 🧠 Explanation: • When the JVM loads the class, all static blocks execute automatically — even before checking for the main() method. • The System.exit(0); line stops execution before the JVM looks for main(), preventing the usual “main method not found” error. ✅ Output: 10 This is a fun trick to understand how class loading and static blocks work in Java. Not practical for production — but a great interview or concept question! 😉 #Java #Programming #LearnWithHarsh #CodingFacts #JVM #TechLearning

To view or add a comment, sign in

Explore content categories