Error on OCP 1Z0-815 BOOK Deshmukh, Hanumant Page 98
Posted: Sun Feb 09, 2020 10:23 am
In the Page 98 they are a snippet like this.
The book states that 2 objects is created in each iteration and this assertion is not correct. The book states that a String object is created at the int value but in Java 8 they would be a total of 11 objects because this would be translated into StringBuilder and later a call to String() which in each iteration would correctly created 2 objects [1 StringBuilder + 1 String] but in Java 9 and on not StringBuilder is used anymore just creating a String on each iteration for a total of 6 objects i dont think is creating a object for every int value but this is very deep on the internals of the JVM we really dont know if in fact creating and additional object is created here but seems that String is very optimized at this point and will not create a additional object here.
In resume i dont think neither the guys on SO that a additional String object is created for the int value for each iteration.
In fact i made this question on Stack and they agree with that this code in Java>=9 is creating 6 objects and in Java <9 is 11 objects you can check it out.
Best regards.
Code: Select all
public class StringCreations {
public static void main(String[] args) {
String hello = "hello";/*A STRING CREATED HERE*/
for(int i=0;i<5;i++){
hello = hello + i;/*OTHER STRING CREATED IN EACH ITERATION.*/
}
System.out.println(hello);/*6 or 11 objects created at this time?? i think is 6*/
}
}
In resume i dont think neither the guys on SO that a additional String object is created for the int value for each iteration.
In fact i made this question on Stack and they agree with that this code in Java>=9 is creating 6 objects and in Java <9 is 11 objects you can check it out.
Also this question is great on SO.
I think that should change the text and the # of objects created.
Best regards.
