When does the non-static block get executed in java? -


i expected non-static blocks execute @ time of object creation. in following example called static method non-static block executed. i've not created object why 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 

you don't have non-static initialization block in example. block inside of method code gets executed part of method. (nested code blocks introduce new scope, can create variables not visible outside of block.)

it's initializer if it's within class outside of method declaration. if change code move block outside of method:

class example {     static void mark() {         system.out.println("mark method");     }      // it's instance initializer     {         system.out.println("hello");     } }    

then should see instance initializer execute when object instantiated. if don't instantiate object, in example, instance initializer won't run.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -