-3

Scenario 1 :

class A{
  static int foo=56789;
  static{
   foo=999;
  }
  public static void main(String[] args) { 
   System.out.println(foo);
  }
}

Output : 999

Scenario 2:

class A{
  static {
   foo=999;
 }
 static int foo=56789;
 public static void main(String[] args) { 
   System.out.println(foo);
  }
}

Output : 56789

In Scenario 2 how does it allocate memory to foo variable (in static block) as no data type is mentioned along with it(as the code runs from Top to Bottom).

atti
  • 180
  • 2
  • 7
  • 2
    Isn't your question actually the answer to your question? – Marko Topolnik Sep 01 '14 at 13:57
  • Doesn't code normally run from top to bottom? If you swap the order of two statements don't they change the order they are run? Where is the surprise here? – Peter Lawrey Sep 01 '14 at 13:59
  • @PeterLawrey lawrey In scenario 2 how does it assigns the memory to foo variable as no data type is mentioned along with it in the static block – atti Sep 01 '14 at 14:27
  • An instance is allocated at once based on the size of the header and all the field it contains. progressively extending the instance would be extremely expensive. As soon as the object is created, and before you start initialising it, all the memory it uses and all the fields it will ever have, already exist. – Peter Lawrey Sep 01 '14 at 14:30
  • @PeterLawrey can you please explain in context of the above example – atti Sep 01 '14 at 14:32
  • In the above context, there is an object which holds all the `static` fields. It is created when the class starts to be initialised. At this point all the data/memory for all the fields exist and will be all `0` or `false` or `null`. Once memory has been allocated, the static initializer method is called and it sets all the fields, running from top to bottom. Note: all the code is in this one method whether you use definition or static blocks. BTW The method is called `` in byte code. – Peter Lawrey Sep 01 '14 at 14:38

1 Answers1

0

Static blocks/variables executes in the order they placed in the source code. i.e the order you are seeing with your eye.

Top to Bottom.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307