wood burning stoves 2.0*
The moose likes Java in General and the fly likes Help with class initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Help with class initialization" Watch "Help with class initialization" New topic
Author

Help with class initialization

Jim Sera
Greenhorn

Joined: Jul 28, 2005
Posts: 11
I have this code sample:


This code prints a, c and b as the output. I understand most of it but someone please explain to me how the b is output. How is the code s1 = sM1("b"); executed and why is it executed last?

My initial impression was that it will be a compiler error because there is a semi-colon after the static String s1 = sM1("a"); statement and the code between the following { } is not part of the static initialzation. can someone explain please.

[ EJFH: Added CODE tags. ]
[ July 29, 2005: Message edited by: Ernest Friedman-Hill ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

Welcome to JavaRanch!

The code after the static String member declaration is an instance initializer block. Since you understand static initializers, instance initializers shouldn't be a problem. An instance initializer looks like a static initializer, only without the "static" keyword. They're run, in order, conceptually before the constructor runs for each instance of the class.

So there are two calls to sM1 during the loading of this class (before main() even runs) and a third call during the "new InitTest()."


[Jess in Action][AskingGoodQuestions]
Jim Sera
Greenhorn

Joined: Jul 28, 2005
Posts: 11
thanks very much Earnest
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Help with class initialization
 
Similar Threads
Static Initializers.
Static and Instance Blocks..
Doubt
Initializing Sequence
initialization sequence - what is done first?