• Post Reply Bookmark Topic Watch Topic
  • New Topic

Strings  RSS feed

 
Jim Frank
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this:
String literal = "";

String getString(){
return (new)String("Bob");
}

literal = getString();

The same as this:
String literal=(new)String("Bob");
 
James Phoenix
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. Because you're making a new String object and returning it, it's essentially the same as creating the returned String object.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Sir Phoenix",

There aren't many rules that you need to worry about here on the Ranch, but one that we take very seriously regards the use of proper names. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
JavaRanch Sheriff
 
Jim Frank
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So the literal String in the first example will be garbage collected, unlike a literal?
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Frank:
So the literal String in the first example will be garbage collected, unlike a literal?


What do you mean? If you create a new String it will be eligible for collection when there's no longer a reachable reference to it. However, the actual literal "" will never be collected, it will remain in the literal pool. The distinction between creating it with a variable initializer and returning it from a method is irrelevent. If it's not a literal, and in your case it's not because you explicitly created a new String, then it can become eligible for collection.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!