Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Help with class initialization

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • 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: 24203
43
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
thanks very much Earnest
 
I just had the craziest dream. This tiny ad was in it.
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic