-4

I expected that non-static blocks always execute at the time of object creation. But in the following example I called the static method but the non-static block executed. I've not created any object so why does the non-static block execute?

class Example {
  static void Mark() {
    System.out.println("Mark method");
    {
      System.out.println("Hello");
    }
  }
}   

public class StaticObject {
  public static void main(String[] args) {
    Example.Mark();
  }
}

Result:

Mark method
Hello
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Albertkaruna
  • 85
  • 2
  • 11

1 Answers1

9

You don't have a non-static initialization block in your example. A block inside of a method is just code that gets executed as part of the method. (Nested code blocks introduce a new scope, so you can create variables that are not visible outside of the block.)

It's only an initializer if it's within the class but outside of a method declaration. If you change the code to move the block to outside of any method:

class Example {
    static void Mark() {
        System.out.println("Mark method");
    }

    // now it's an instance initializer
    {
        System.out.println("Hello");
    }
}   

then you should see the instance initializer execute when the object is instantiated. If you don't instantiate an object, as in your example, then the instance initializer won't get run.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276