File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Number of String objects created" Watch "Number of String objects created" New topic

Number of String objects created

Jarle Eide

Joined: Apr 13, 2007
Posts: 3

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?

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
I agree. Here's the link:
subject: Number of String objects created
It's not a secret anymore!