Hello,
Stumbling upon the same issue as Raul, I have to make a remark. Roel repeatedly states that for the certification exams (like OCA and OCP) there is no need to know about this optimization performed by the
Java compiler, nor the bytecode, and that the code can be evaluated without such knowledge.
I disagree with this statement: the answer to the question being discussed cannot be known _without_ such knowledge as above. I will argument my claim.
Roel, you correctly state the following:
Roel De Nijs wrote:
If one of them is not a compile time constant, a StringBuilder will be used to concatenate (also a compiler optimization). As shown in this snippet (followed by the decompiled code and the resulting bytecode)
Now, in the question in the book, we have the statement s=" "+i; which is looped 1000 times. Here, i is not a compile time constant, thus for each concatenation we get the following replacement code:
Meaning, for each concatenation we have one StringBuilder object and one
String object created from the toString() method.
Even more: the StringBuilder(String) constructor allocates a buffer containing 16 characters. Which is a char[16] array, which is also an object.
So, per concatenation - meaning per each iteration in the loop - we have 3 NEW objects being created: a StringBuilder, the corresponding char[] array, and a String object obtained from the toString() method.
Multiplied by 1000 iterations, we get something like 3000 objects. In any case not the stated answer B (about 1000).
In the end I have to say that not only the statement in Chapter 4 is wrong in the book, but also this question from the Self
Test. And if for the
OCAJP exam the underlying mechanisms regarding this question are out of scope for the exam, then the question is not appropriate.
If I am missing something, then PLEASE instruct me as to how should I cast my judgement when trying to asnwer such a question. Thank you for answering me!