Reputation: 21435
I am going through the Java ranch site for Strings and came across the statement under Garbage Collection section that says:
Unlike most objects, String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection.
If I have a web application with a Java bean class for example - employee as
public class Employee {
int employeId;
String firstName;
String lastName;
String fullName = firstName + lastName; // or firstName.concat(lastName);
.... Setters & Getters....
}
If the application creates so many employees, so this bean gets populated every time based on request parameters. Also if application provides a search feature where users can look for employees based on first name and last name, so we need to populate this bean and pass it in request scope so user can see the results.
In this scenario the application is creating so many Strings for firstName, lastName, and fullName. As per the explanation given in Java ranch site, do we get OutOfMemory
errors after some time? Also suppose if I have just firstName and lastNname which are again Strings, we face same issue even if we don't have fullName?
Upvotes: 0
Views: 103
Reputation: 882336
Strings are not the same as string literals.
A string literal is something like "paxdiablo"
in your source code. Getting a string from a user does not create a string literal, it just creates the string data itself, which is subject to garbage collection.
Basically, what that snippet is stating is that, in the following code:
String xyzzy = "plugh";
the "plugh"
string literal will never disappear into the bit-bucket, although some other constructed string (ie, non-literal) may.
Upvotes: 6