This week's book giveaways are in the Jython/Python and Object-Oriented programming forums.
We're giving away four copies each of Machine Learning for Business: Using Amazon SageMaker and Jupyter and Object Design Style Guide and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning for Business: Using Amazon SageMaker and JupyterE this week in the Jython/Python forum
or Object Design Style Guide in the Object-Oriented programming 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
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Knute Snortum
Sheriffs:
  • Liutauras Vilda
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Joe Ess
  • salvin francis
  • fred rosenberger

Order of execution of initialisers

 
Ranch Hand
Posts: 85
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On page227 in the book 'Certified Associate Java SE 8 Programmer I' by Jeanne Boyarsky and Scott Selikoff, chapter 4 review question 22 asks what the output of the following code would be:




On line 5 in the OrderDriver class, we refer to the Order class for the first time. At that point, the static blocks are initialized in order (or in this case, the only static block defined on lines 8 - 9 in the Order class).

However, because static initialization is only run once, we see "u" printed out from both lines 5 and 6. For this particular case, I assume that's true because there's only one static block (defined on lines 8 - 9). I confirmed this by adding another static keyword on line 10 (which was not in the book's version of the code, so I commented it out). I found that if that static keyword was not commented out, the output would be:
sy sy syxx
With the code the way it is now, the actual output is:
s s sxyxy

The answer key goes on to explain that on line 7 of the OrderDriver class, we create a new Order object. Because of Java's order of initialization, this generates the first sxy. What I don't understand is why the second new Order(); on line 8 only prints xy. If the s of the first sxy was capable of being generated from the static block, then doesn't that mean new Order(); object should be capable of calling both static and instance material, rather than just instance material? If so, then shouldn't xy be sxy instead?

Oh, and where the heck is our s from the print statement on line 9?

If there were no contradicting answers to any of my questions, I believe the output would be:
s s sxysxys
 
Marshal
Posts: 67533
257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you get "u" from?

Sam Peterson wrote:. . . What I don't understand is why the second new Order(); on line 8 only prints xy. . . .

No, new Order() in line 8 doesn't print anything. It is the System.out.println(...); in line 9 that prints something.
Remember the order of execution:-
  • 1: The static field is loaded and initialised to "" when the class is loaded.
  • 2: Immediately thereafter, the static initialiser runs and changes the field to "s". That static initialiser only runs once. The "s" is printed twice.
  • 3: An object is created. The superclass constructor (=Object()) runs. Next, the two instance initialisers run, in order line 6 before line 11. The field has "x" and "y" added in that order. Then the (remainder of) the constructor (a default constructor) runs.
  • 4: An object is created. The superclass constructor (=Object()) runs. Next, the two instance initialisers run, in order line 6 before line 11. The field has "x" and "y" added in that order. Then the (remainder of) the constructor (a default constructor) runs.
  • 5: You will notice that Nos 3 and 4 are identical. By now the field is "sxyxy" and we now print it to screen.
  •  
    Sam Peterson
    Ranch Hand
    Posts: 85
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell, I apologize, but due to goofy forum error detection, I've been forced to use attached images to quote your post and construct my next question. Maybe the moderators should do something about this.
    ForbiddenAbbreviationsInForums.PNG
    [Thumbnail for ForbiddenAbbreviationsInForums.PNG]
    ForumsWouldNotLetMeDoThis.PNG
    [Thumbnail for ForumsWouldNotLetMeDoThis.PNG]
     
    Campbell Ritchie
    Marshal
    Posts: 67533
    257
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When I said “s” is printed twice, I meant that you have two print() statements printing “s” in lines 5 and 6.
    I cannot see a third plain simple, “s”, but, “sxyxy”. You have “xy” duplicatedtwice because you are calling the constructor (and therefore the instance initialisers) twice. Please explain what you don&apost understand about my explanation and I shall try again. What happened when you ran the code?
     
    Saloon Keeper
    Posts: 21625
    147
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When you have initializer code in a Java class, basically all of the inilializer code is scooped up and used to build and anonymous initialization method that gets invoked when the class is loaded for the static initializers or before the constructor (if any) is called for member initializers. The tricky part in this exercise is that there is not a terminator between the {result += "s";} and {result += "y";} initializers, so both of them are in the static domain. If the code had been:
    the semi-colon after the first clause would terminate the statement, kicking the second one back to member scope, and that would change everything.

    Creating a multi-part statement in the form "{}{}{}{}..." is obviously a very dangerous practice and the proper way to address it isn't to flunk the student for mis-interpreting it, it's to flog the monster who created such an abomination until they promise never, ever, ever to do something as horrid as that again.
     
    Campbell Ritchie
    Marshal
    Posts: 67533
    257
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It's Jeanne you are threatening to flog to within an inch of her life
    In her defence, this code is out of a cert exam revision book, and cert exams allow bad code style which would get you keel‑hauled anywhere else.
     
    Tim Holloway
    Saloon Keeper
    Posts: 21625
    147
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:It's Jeanne you are threatening to flog to within an inch of her life

    In her defence, this code is out of a cert exam revision book, and cert exams allowwallow in bad code style which would get you keel‑hauled anywhere else.



    I'm an equal-opportunity flogger, and I'll leave it to the Powerful to let their friends off easy.

    The reason I never picked up any certs is precisely because they don't focus on the stuff that indicates competence, but rather on presenting obscure puzzles and obsessing about minutiae. Last time I tried a study guide I ended up hurling it across the room when I got to the 47 different types of fine-grained Java assertions.

    I used the assert statement extensively in C and C++. I've almost never used it in Java and never at all with that level of granularity. It's not that I don't appreciate fine control, but that that level of detail is best relegated to the lumber-room of one's reference library not crowding out developing a proper mastery of the language. Very likely the 47 options have changed since then and few cared and those who memorized it now have false information. In Real Life, test frameworks like jUnit have their own assertion mechanisms and fine-grained logging mostly fills in the rest.

    In Real Life, code like the example given here would be buggy code and rather than determining what the output should be the programmer would have output, they'd know what the proper output was supposed to be, and the problem would be inverted: find the reason for the difference.
     
    Campbell Ritchie
    Marshal
    Posts: 67533
    257
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Tim Holloway wrote:. . . allowwallow in . . .

    Only just noticed that bit. Hahahahahahahaha!

    Agree: cert exams don't test anybody's ability to code anything. Maybe they have that format because it lends itself to automatic marking.
     
    Tim Holloway
    Saloon Keeper
    Posts: 21625
    147
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    One of the reasons I thought so highly of the RHCE exam was that it essentially tested what I'd do in everyday life: take a cold iron box, and, over about 4 hours, bring it up to a fully-functioning server. No obscure tricks, no puzzles, just take ordinary equipment (I'll allow ordinary defects like a bum NIC or bad disk) and make it work.

    Unfortunately, the software equivalent of that sort of demonstration would take several weeks, which doesn't admit itself well to a testing-facility environment.

    What would actually be more realistic is some sort of guild certification system. However, guilds/unions have an unfortunate element of political/good-old-boyism, and software developers often aren't the most socially graceful people.

    I suppose the best approximation our current era affords is for people to publish "master pieces" as projects on github.
     
    Sheriff
    Posts: 14764
    245
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I, too, don't put much stock in programming certifications as a gauge for competence. However, they do give people with less real-world experience a slight advantage. I got my first Java programming gig exactly because I had a SCJP credential on my resume.

    I'm looking into apprenticeships and mentoring programs as a way of establishing a pipeline of reasonably and reliably competent talent available to my organization. Will let you guys know how it goes in a few months.
     
    Tim Holloway
    Saloon Keeper
    Posts: 21625
    147
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Maybe we should employ a blockchain model. Establish a "web of trust" where established developers could vouch for the talents of less-well known people with peer scoring of the strength of the up-chain ratings.

    Nah. People would probably start suing over bad ratings.
     
    Junilu Lacar
    Sheriff
    Posts: 14764
    245
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A Blockchain WoT model is actually pretty interesting, barring the complications like you mentioned. I think I might even steal that idea and use it as a training project for apprentices to work on.
     
    Campbell Ritchie
    Marshal
    Posts: 67533
    257
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Tim Holloway wrote:. . . . Establish a "web of trust"  . . . Nah. People would probably start suing over bad ratings.

    That is called a reference. And why do you think people will start suing?
     
    Tim Holloway
    Saloon Keeper
    Posts: 21625
    147
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:

    Tim Holloway wrote:. . . . Establish a "web of trust"  . . . Nah. People would probably start suing over bad ratings.

    That is called a reference. And why do you think people will start suing?



    There is a difference. When I give references, they're as likely to be character references by people who are in no position to judge my competence. What I'm proposing here would be more like the masters of a guild recommending elevation based on professional knowledge of the candidate. And, it allows people who are not easily contacted directly by HR to add their upvote because those people might be in turn vouched for by someone closer to home, a là "Kevin Bacon". So by "start", I mean a whole new system.

    It would probably actually be harder to sue that way because the scope of certification would be so narrow. Although you could also channel additional things like work ethic, quality of work, timeliness of delivery, etc with separate rankings, and while it doesn't prevent a clique from blackballing, the world-wide scope means that you could potentially enlist a counter-clique and let them battle it out where people would get their recommendation strength downgraded (weakened) for being spiteful. Things like this have, as an example, played out in the Wikipedia project.

    And it feeds back. If Jim Gosling endorses Alan Kay who endorses Bjarne Stroustrup who endorses me I get a strong chain, but if Bjarne thinks I'm an incompetent jerk not worth promoting and I have to rely on chains like Harvey Foonman who is attested to by Nikolai Ceaușescu and Benito Mussolini, I have a weak chain.
     
    Junilu Lacar
    Sheriff
    Posts: 14764
    245
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Tim Holloway wrote:attested to by Nikolai Ceaușescu and Benito Mussolini, I have a weak chain.


    or a chain from hell, perhaps literally.  
     
    Sam Peterson
    Ranch Hand
    Posts: 85
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Okay folks, lets get back to the topic shall we?

    Campbell Ritchie wrote:Please explain what you don&apost understand about my explanation and I shall try again. What happened when you ran the code?



    1. The only block that is actually static in Order is line 9. Lines 5 and 6 print that out twice in OrderDriver.

    2. In OrderDriver, and instance of order is created not once, but twice on lines 7 and 8. The true mystery regarding that is why s only printed once.

    3. If an instance does not include static variables, then the s shouldn't be there, and the print statement on line 9 should only add xyxy to the final output.

    4. If the instance created on lines 7 and 8 in OrderDriver DO include the initialization of static variables, then xyxy should actually be sxysxy.

    5. And yet, only one of the xy has an s appended to the left of it.

    The final output is:
    s s sxyxy

    So where is the other s, or why is the lone s there at all?



     
    Marshal
    Posts: 24961
    61
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sam Peterson wrote:3. If an instance does not include static variables, then the s shouldn't be there, and the print statement on line 9 should only add xyxy to the final output.



    Static variables are initialized when the class loads. This happens exactly once during the lifetime of the class, and it happens before any instance initializations take place. It can even happen if no instance initializations take place.
     
    Campbell Ritchie
    Marshal
    Posts: 67533
    257
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Please avoid coloured text; I have changed it to all black, so people can actually read it.

    1. The only block that is actually static in Order is line 9.

    Yes.

    Lines 5 and 6 print that out twice in OrderDriver.

    No. Lines 5‑6 print the value of the field; they don't do anything to the static initialiser.

    2. In OrderDriver, and instance of order is created not once, but twice on lines 7 and 8. The true mystery regarding that is why s only printed once.

    No mystery. As Paul has told you, the static initialiser runs only when the class is loaded, not when it is instantiated.

    3. If an instance does not include static variables, then the s shouldn't be there, and the print statement on line 9 should only add xyxy to the final output.

    A print statement doesn't add anything; it displays it. What you are thinking is that the instantiation will remove the "s" from the field, but there is nothing about removing anything. The only operator used in the instance initialisers is +=. Instance code can alter a static variable, but not vice versa.

    4. If the instance created on lines 7 and 8 in OrderDriver DO include the initialization of static variables, then xyxy should actually be sxysxy.

    But instantiating a class does not cause its static initialisers to be called. So there is no additional “s”. (Actually, that would have added “s” twice, making the field into “ssxysxy”.)

    5. And yet, only one of the xy has an s appended to the left of it.

    No, none of the “xy”s has “s” appended to it, nor prepended. The “s” was there first, so the first “xy” was appended to the “s”. “Appended”, when used about text, means attached on the right.
     
    I can't renounce my name. It's on all my stationery! And hinted in this tiny ad:
    Java file APIs (DOC, XLS, PDF, and many more)
    https://products.aspose.com/total/java
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!