Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Number of String objects created Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Number of String objects created" Watch "Number of String objects created" New topic
Author

Number of String objects created

Jarle Eide
Greenhorn

Joined: Apr 13, 2007
Posts: 3
Hi,

I'm using the SCJP5 Study Guide by Sierra and Bates (great book by the way) to study for the exam, and I have a question regarding an example in the book on String objects and immutability:

1. String s1 = "spring ";
2. String s2 = s1 + "summer ";
3. s1.concat("fall ");
4. s2.concat(s1);
5. s1 += "winter ";
6. System.out.println(s1 + " " + s2);

Now, the book states that 8 String objects are created in total: "spring ", "summer ", "spring summer ", "fall", "spring fall ", "spring summer spring", "winter", "spring winter". My question is then: would not line 6 also create some String objects, at least the object with value " ", but also (s1 + " ") and (s1 + " " + s2) during the + operations?


jarle
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
I think 2 strings on line 6:

ONE in constant pool: ""
SECOND when result of operations is converted to string by calling toString() on StringBuilder





20: here's empty string ""
29: here's toString()
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
You can also search in previous topics. I rememeber at least one such topic. Just search for "spring summer" ;-)
Michael Raymond Jr.
Ranch Hand

Joined: May 16, 2005
Posts: 178
System.out.println(s1 + " " + s2);


How do we know it's actually concatenating them? At least for s1 and s2, perhaps println() just references their memory locations, prints the data in those references, and doesn't actually do any string manipulation hence the reason no new objects are created. Dunno about the " " though.

Just a shot in the dark.


Scooby Snacks for everyone...<br /> <br />SCJA, SCJP 1.4
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Number of String objects created
 
Similar Threads
How many String objects are created.
How many String Object are created in the following code ??
Please clarify on number of strings
String Object
How many String objects are REALLY created?