• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String in VM string-pool

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[From javacoding.net mock exam] :
How many Strings are in the VM string-pool after executing this code fragment :

The answer is 2.
Could anybody explain this ?
I though that in the case above, only 1 string literal is store in the VM string-pool.
 
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well you know that if 2 String references have the same string value at compile time due to the use of a String "literal" if you can call it so, then they both share the same String object, they both point to the same String, this happens in the first 2 lines of code.
In the third line, you instruct the compiler to construct a "new" object of type String with a value - maybe equal to another existing string in the string pool - and assign the reference to a String variable.
String S3 = new String("The same existing String")
result is 2 string objects.
HTH
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At last week's New England Java Users' Group, Joshua Bloch said that there never should have been a String(String s) copy constructor. Since strings are immutable there is no reason ever to make a copy of one.
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A good dicussion about Strings:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014328
reply
    Bookmark Topic Watch Topic
  • New Topic