Reputation: 6265
Given this code:
if(somecondition) {
String one = "one";
//print one;
}
This string will only be generated when that condition is true?
Appreciate any help.
Edit:
With String pooling, is it safe to say that String one
will be added to the pool regardless of a condition.
So, if a variable needs to be resolved from an object, what will happen?
Say,
String hello = "Hello Mr " + user.firstName();
How will this be added to String pool? And when it does get added to String pool, it will not create new String literals right (unless user.firstName() changes).
Upvotes: 0
Views: 796
Reputation: 70909
The string is generated at the time you typed it; but, for that answer to make sense, we need to walk it's life through the transformations in the build and launch of the application.
*.java
file.*.class
file as part of the constant pool entries.So, there's multiple places where it could be "created" depending on your definition of which kind of "creation" you wish to use.
Now, in your first example, the String object isn't realized when you use the string, but when you use the *.class
file. However, it's not reference by the running program until you enter the method.
Finally, with String pooling, every time a string is about to be created, the existing pool of strings is searched, and if a matching entry is found, the matching entry is used instead of creating a new string. This reduces the number of strings in a runtime, at the cost of a lot of string searching.
Due to the details of your code, you have three different strings that are eligible for pooling ("Hello Mr ", the value of user.firstName()
, and the string combining them both). "Hello Mr " would be pooled with the class loading (assuming pooling is being done). The value of user.firstName()
would have happened when the value for the return was originally created. The resulting combined string would be pooled just before the assignment (or reference from the pool, if it already exists in the pool).
Upvotes: 4