-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).

6
  • 2
    Isn't your question actually the answer to your question? Commented Sep 1, 2014 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? Commented Sep 1, 2014 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 Commented Sep 1, 2014 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. Commented Sep 1, 2014 at 14:30
  • @PeterLawrey can you please explain in context of the above example Commented Sep 1, 2014 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

-3. come on ..come on. I'l cheer up you guys. ha ha

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.