2

I found something like this and I have a question why this works and how JVM parses it?

class app {
    public static void main(String[] args) {
    }

    public void foo() {
        System.out.print("Hello World");
    }

    {
        foo();
    }
}

Of course, there's not showing message (because foo() is not in main function), but I'm thinking why code in just {} are not throwing an error.

Here's in online compiler: http://goo.gl/TLv3JH

Makoto
  • 104,088
  • 27
  • 192
  • 230
Siper
  • 1,175
  • 1
  • 14
  • 39

2 Answers2

4

What you have is an instance initializer. The code in this block is executed every time you create a new Object from type app. It is the same as a static constructor, only that it is run every time you create an instance, not only once.

The instance initializer runs before the constructor.

For detailed information see documentation

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword,

bpoiss
  • 13,673
  • 3
  • 35
  • 49
4

In Java, your example is known as an instance initializer. It will be run every time a new object app is called.

It can be useful for different reasons. As an example:

public class App{

    public static void main( String[] args ){
        new App();
        new App();
    }

    static{
        System.out.println( "static initializer" );
    }

    public App(){
        System.out.println( "constructor" );
    }

    {
        System.out.println( "instance initializer" );
    }
}

Will output:

static initializer
instance initializer
constructor
instance initializer
constructor

So, a static initializer runs once when the class if first loaded, before anything else. An instance initializer runs at each instantiation before the constructor.

Derlin
  • 9,572
  • 2
  • 32
  • 53