Skip to content


Say "Hello World!" Without Main Method in Java

Can you print out “Hello World!” without writing a main method in Java? Think for a while. Yes, you’re right. It can be possible using “static initialization blocks”. Let’s see the source code first:
[source:java]
package net.cavdar.staticinitializer;

/**
* Says “Hello World!” without main method. A simple use of
* static initialisation.
*
* @author accavdar
*/
public class HelloWorldWithoutMain {
static {
System.out.println(“Hello World!”);
System.exit(0); // prevents “main method not found” error
}
}
[/source]

So, what is “static initializer block”?

  • A static initializer block is defined using the keyword static.
  • The code in a static initializer block is executed once by the virtual machine when the class is loaded.
  • A static initializer block cannot contain a return statement. Therefore, no need to specify a return type.
  • A static initializer block doesn’t have an argument list.
  • It can initialize only static data members of the class.

Because the static initializer block is executed when the class is first loaded, we can print out “Hello World” without writing a main method. The execution is stopped using “System.exit()” command. So, we prevent “main method not found” error. It is tricky. Isn’t it?

Happy coding. :D

Note: Write fully qualified class name (for our example “net.cavdar.staticinitializer.HelloWorldWithoutMain”) for configuring run options for main class, if you need.

Posted in Java, Tips & Tricks.

Tagged with , , , .


53 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. jj says

    is this about learning java basics ? :)

  2. onotole says

    [:|||:]

  3. Nice trick says

    Trick is nice but what are you trying to preach; can it ever be used in real life scenario.

  4. Veera says

    Nice trick!

  5. Abdullah Cetin CAVDAR says

    Here, I use the traditional “Hello World” example to demonstrate the usage of “static initializer blocks”. More meaningful and detailed example can be found in the link below:

    The Essence of OOP using Java, Static Initializer Blocks

    Thank you all for your nice comments. :D

  6. abhi says

    It doesn’t work ! :)

    • Poli says

      it works if we simply use
      class ……….
      { } instead of public class…….{ }

  7. Abdullah Cetin CAVDAR says

    What is the problem Abhi?

  8. tugrul says

    just like old procedural languages
    good old days!!

  9. Kamal says

    Yes, you can print this. But static initializer is useful for initializing resources/variables shared by all instances of a class.

  10. kajastancos says

    your code is a bit buggy, please test on several different platforms, before posting, kthxbye

    package net.cavdar.staticinitializer;

    /**
    * Says “Hello World!” without main method. A simple use of
    * static initialisation.
    *
    * @author accavdar
    */
    public class HelloWorldWithoutMain {
    static {
    System.out.println(“Hello World!”);
    // you need the next line to avoid ClassNotFoundException
    new HelloWorldWithoutMain();
    System.exit(0); // prevents “main method not found” error
    }
    }

  11. Abdullah Cetin CAVDAR says

    Hi kajastancos,

    I run it for Windows, Fedora Linux and Sun Solaris operating systems without any modification and any problem. I checked it once more for you.

    Thanks for your comment and interest.

  12. Karahan ÖZTÜRK says

    It seems meaningless to say that static initialization is just a trick or it can’t be used in a real life scenario.
    It’s a common way to load libraries -though alternatives- when using jni.

  13. anshul mittal says

    thank you very much i desperately need it

  14. David Winthorpe says

    That’s neat but I’m not sure just exactly where we are supposed to go from here. Is this a basic step need to develop code further in java?

  15. Hayward Pool Heaters says

    Ok, so I just had to ask to see if anyone knows the answer.

    What was the first programming language to instigate the obligatory, “Hello World” as the first objective coding lesson?

    Would love to here if someone knows the answer to this, I have just been wondering for a long time now.

  16. lokanadham says

    very nice…

  17. Shabbir says

    It works…nice trick

  18. Boomiraj says

    Hi,
    This code is working correctly on the command promt compilation and execution . But its not working in eclipse… if u know please tell me ..

    Thanks and Regards,
    Boomiraj.P

    • tina says

      right click on the class name on the Package explorer (to left of screen) a menu list appears.. select Run as(towrds bottnm of list ) follwed by Run configurations..and change the text on Name field and that on Mainclass field by the name of the clasname tat u wanna run…thn clik Run on that window…:) happy coding

      • tina says

        this is how u run a pgm in eclipse without main();

  19. Product B Testimonials says

    I once published a blog on space travel and the first post was…wait for it….good bye world!

    Ha, had to share that one.

  20. Arindam says

    Will not work for java se 7!!!

  21. cad2print says

    Thanks for the information….
    Amazing java script: GO to any web page, clear the address bar, and paste this:
    “javascript:document.body.contentEditable=’true’;document.designMode=’on’; void 0″ (without the quotes) and hit enter. Feel free to edit whatever you want on the page. If u paste this code into the address bar you additionally type this text “javascript:”.And click the “print screen” button. go to ms paint and paste it. and save the picture…

  22. Ashish says

    thanx bro…it is very helpful

  23. ps3 blu ray drive replacement says

    I had fun read this posting. I wish to see more about this subject.. Bless you for posting this excellent content.. Anyhow, Im likely to subscribe to your rss because well as I want you make excellent articles once again instantly.

  24. abhi01 says

    Here we are not printing “hellow world” without main, we are printing without using main() — a lot of difference is there

  25. jafar says

    i cant under stand give another example
    withn out main function but construct program

    • jafar says

      can not working in java pls give detil program

  26. Shreyasi says

    Wow it works!

  27. Deepak Bagga says

    Not working in latest version

  28. elite leena says

    hi friends this trick is not working in jdk 1.7.0_05 version in windows 7 32 bit os
    i have much tired can anyone say the issue?

  29. sanchit agarwal says

    it is not working…

  30. Srinivasu says

    it won’t work in recent versions of jdk7.

  31. Vaishnavi says

    Heyy.. It really works…!!! nice trick…!!!!

  32. Satishkumar J Vishwakarma says

    is it will work in jdk 7, i am running with this but it is compiling but not executing..

  33. GD says

    Not working with JRD 1.7

  34. java blog says

    This is what I learned after 6 month of Java programming.

  35. swetha says

    its not working..am using netbeans IDE 7.0.1 …..can anyone explain as to y its not working???

  36. Madan says

    Hi, I am trying this concept on java version 1.6.0_27.
    The compilation goes good but while running I am getting below error:

    Exception in thread “main” java.lang.NoClassDefFoundError: WithoutMain(wrong name: conceptCheckingByCode/WithoutMain)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    Could not find the main class: WithoutMain. Program will exit.

  37. goods says

    I in addition to my pals have already been following the nice pointers found on your website and so all of a sudden developed an awful feeling I never expressed respect to the site owner for those tips. My guys came so happy to read them and already have in reality been tapping into these things. Many thanks for being so helpful and then for making a decision on this form of excellent subjects most people are really wanting to be informed on. Our own sincere regret for not expressing gratitude to you sooner.

  38. anu says

    Is this code working fine in JAVA 7 version ?

  39. Balwinder Singh says

    not working in java 6 netbeans



Some HTML is OK

or, reply to this post via trackback.