• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Number of String objects created

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can also search in previous topics. I rememeber at least one such topic. Just search for "spring summer" ;-)
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic