Hacker News new | ask | show | jobs
by johnyzee 828 days ago
You can write write code outside of methods in a Java class, called an initializer block:

  class MyClass {
    {
      System.out.println("Hello World!");
    }
  }
This will run when an object of the class is instantiated. So not useful for the case in question (you could get rid of the class declaration but would presumably still need a main method).

(It's also pretty poor style, but occasionally useful in a pinch, like when instantiating an anonymous inner class, which has no constructors that take arguments)