-
Book Overview & Buying
-
Table Of Contents
OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
By :
A small program can create a lot of String objects very quickly. For example, how many do you think this piece of code creates?
10: String alpha = "";
11: for(char current = 'a'; current <= 'z'; current++)
12: alpha += current;
13: System.out.println(alpha);
The empty String on line 10 is instantiated, and then line 12 appends an "a". However, because the String object is immutable, a new String object is assigned to alpha and the “” object becomes eligible for garbage collection. The next time through the loop, alpha is assigned a new String object, "ab", and the "a" object becomes eligible for garbage collection. The next iteration assigns alpha to "abc" and the "ab" object becomes eligible for garbage collection, and so on.
This sequence of events continues, and after 26 iterations through the loop, a total of 27 objects are instantiated, most of which are...
Change the font size
Change margin width
Change background colour