Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number of String objects created

 
Jarle Eide
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also search in previous topics. I rememeber at least one such topic. Just search for "spring summer" ;-)
 
Michael Raymond Jr.
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic