I'am studying the book OCA Oracle Certified Associate Java SE 8 Programmer I from Boyarsky and Selikoff.
In Chapter 4 in Review Questions number 22, page 227, I don't understand, why the result "t t tcrcr" is right!
Sorry, I had to change the original letter from the book Question, because I received every time this error:
We're sorry, but your post appears to contain abbreviations that we don't like people to use at the Ranch. Because JavaRanch is an international forum, many of our members are not native English speakers. For that reason, it's important that we all try to write clear, standard English, and avoid abbreviations and SMS shortcuts. See here for more of an explanation. Thanks for understanding.
If the abbreviation occurs within code, you can use code tags to post it successfully. If the abbreviation is a variable name, you can use the tt tag.
The specific error message is: "u" is a silly English abbreviation; use "you" instead.
With tt tag I also received the same error, so I changed the letter from "u" to "t"!!
In line 6-8 only the first block belongs to the static field, the second, on line 8 is only an instance initializer, right?
The first two "t" in the answer i understand "t t " The first time we call new Order() the result is "t" and then 2 instance initializers are called, first "c", then "r" and after that we have "t t tcr". But after the second call of new Order() why we receive only "cr"?? The variable result is static. Also the variable is still "tcr", why the second call of new Order() only gives "cr"??
Can someone explain me what happens, step by step.Static initializers would be called only once, I thought. Or is result after every creation of an object Order result=""?
Yes. line 8 is an instance initializer. There are two instance initializers in this code.
t - first call only has the static initilizer run
t - second call has no change so the previous value
tcrcr - third call has the original value plus the two "cr" from each of the two instance initializers
your analysis is correct. Let's follow what is happening step by step.
1) when the class is loaded, result is initialized to "t", according to the static initializer at line 7.
2) so, OrderDriver, line 17, will print "t "(with a space)
3) and in line 18, the same is repeated, on the same line. so we get "t t "; result is still "t", by the way.
Then, in line 19 and 20, new OrderDriver() is executed. That means that the instance initializer is performed twice, making result equal to "tcrcr". Finally this is printed out, but since the exercise uses "print" and not "println", "tcrcr" is output right after what we already had. That was "t t ", so we get in the end "t t tcrcr".