Hi, All:
Just verifying Java Compiler optimization and string literals. If I have
the following method, how many String objects are created in the for loop:
public void method() {
for(int i = 0; i < 1000000; i++) {
System.out.println("xxx");
System.out.println("xxx");
System.out.println("xxx");
System.out.println("xxx");
System.out.println("xxx");
}
}
I say one object is created for the entire for loop and the code is fine, my
colleague says many and this code is inefficient. Any people want to
comment?
Thanks,
John
Timo Stamm - 21 May 2006 03:32 GMT
John and Diane Curley schrieb:
> Hi, All:
>
[quoted text clipped - 14 lines]
> colleague says many and this code is inefficient. Any people want to
> comment?
Only one String object is created. See $3.10.5 of the Java Language
Specification.
Timo
java-interview - 21 May 2006 10:36 GMT
only one String Object will be created
java-interview - 21 May 2006 10:37 GMT
only one String Object will be created
Tony Morris - 21 May 2006 11:50 GMT
> Hi, All:
>
[quoted text clipped - 17 lines]
> Thanks,
> John
None are create in the for loop. One is created at class load time from the
class' constant_pool.
See if this helps:
http://jqa.tmorris.net/GetQAndA.action?qids=68&showAnswers=true
--
Tony Morris
http://tmorris.net/
Chris Uppal - 21 May 2006 11:53 GMT
> [...] how many String objects are created in the for loop:
>
[quoted text clipped - 10 lines]
> I say one object is created for the entire for loop and the code is fine,
> my colleague says many and this code is inefficient.
You and your collegue are both wrong, but he is a lot more wrong than you ;-)
/No/ strings are created in that loop. One instance of String ("xxx") is
created around about the time when the class is loaded. In the loop you refer
to that single pre-existing String five million times; you do not create any
strings at all.
-- chris