• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number of Strings created. String eligible for garbage collect

 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am interesting when we pass string literal to constructor/metod is created new String object (and placed in String constant pool)?


and i little confused about string literal when created string using new String:
- literal "hello" in this case not treat as String object and not place in String constant pool, or it will treat as String object and place in String constant pool?
and how many strings created by this line? 2 or 1.
and one more String in string constant pooll is not eligible for garbage collect even you asigment null?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sergej Smoljanov wrote:I am interesting when we pass string literal to constructor/metod is created new String object

You don't pass string literals (or any other object instance) to methods - you pass object references to methods. No new object is created. The method just receives a reference to an existing object.

Sergej Smoljanov wrote:and i little confused about string literal when created string using new String:
- literal "hello" in this case not treat as String object and not place in String constant pool, or it will treat as String object and place in String constant pool?
and how many strings created by this line? 2 or 1.

The string literal is created when the class is loaded if it doesn't already exist in the string pool. When that line of code is exceuted, a second String will be created with the same value as the string literal.

Sergej Smoljanov wrote:and one more String in string constant pooll is not eligible for garbage collect even you asigment null?

str is not an object - it is a reference variable. Setting it to null just means it no longer references any object. The object it used to reference will still exist, but may be eligible for garbage collection if there are no other references to it, although this is almost never the case for string literals. If you assume that string literals are never garbage collected, it is highly likely you will never be wrong.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic