• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Help with class initialization

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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()."
 
Jim Sera
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks very much Earnest
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic