Skip to content

Hello, World! in Java without main()

March 6, 2011

While I was reading the SCJP book, I came across the concept of initialization blocks, or init blocks for short.

Those blocks of code get executed before any method code is executed.

One kind of these blocks is static init blocks, those get executed immediately after the super constructor has finished execution.

This made me think, “I could output text to the screen without having any methods at all!”.

So, I sat down, fired up vi, and started writing the code.

At first, I had a few problems, I tried to write a method inside the static init block, which was a terrible idea, as the code didn’t compile.

So, I removed the method, and just kept the statements inside the block, it compiled, and then I decided to run it.

It did print the desired text to the screen, but I ended up getting a MethodNotFoundException at the end of execution.

So, I added a call to System.exit() to avoid this, and it worked as if I had a regular main method with the previous code.

Without further ado, here’s the code :


public class Main{
        static{
                System.out.println("Hello, World!");
                System.exit(0);
        }
}

From → Java

2 Comments
  1. david permalink

    It doesn’t work anymore with jdk1.7.xx.

Leave a comment