It's not a secret anymore!
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Help with class initialization" Watch "Help with class initialization" New topic

Help with class initialization

Jim Sera

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

Joined: Jul 08, 2003
Posts: 24199


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

Joined: Jul 28, 2005
Posts: 11
thanks very much Earnest
I agree. Here's the link:
subject: Help with class initialization
jQuery in Action, 3rd edition