-2

Though this is a small question to ask, wanted to understand this strange behavior! Following is the code and the behavior of the code that's in discussion (through the console output).

public class EmptyBracesWithinClass {
    public static void main(String[] args) {
        EmptyBraces eb = new EmptyBraces();
        System.out.println("SYSO within main() method");
    }
}

class EmptyBraces {
    {
        System.out.println("SYSO within empty braces");
    }

    public EmptyBraces() {
        System.out.println("SYSO within constructor() method");
    }
}

Console output:

SYSO within empty braces
SYSO within constructor() method
SYSO within main() method

The question here is, why would the piece of code within the empty braces get executed first during the object instance creation of EmptyBraces class (though it is never declared as STATIC explicitly)?

N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46
  • 1
    Next time: do some prior research; and seriously; I don't get why people are upvoting an obvious duplicate ... – GhostCat Jul 13 '16 at 11:41
  • 2
    for some more info (http://stackoverflow.com/questions/12550135/static-block-vs-initializer-block-in-java) – bananas Jul 13 '16 at 11:46
  • Note: This is not a static initializer, but an instance initializer. – Jesper Jul 13 '16 at 13:54

2 Answers2

6

the piece of code within the empty braces is called instance initializer block. It gets executed before the constructor body (and after the super class constructor is executed) whenever an instance of the class is created.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

This is because before print method excecuted of EmptyBracesWithinClass, you're calling EmptyBraces by instantiate it. so static initializer block run at first and then constructor will run.

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27