You should actually prefer using a StringBuffer or a StringBuilder for such things.
The String Pool has nothing to do with both of your approaches however.
A typical question regarding string pools, will look something like this:
String someString = new String("Shark");
How many strings will be created by the following code snippet? How many strings will exist in the string pool?
And the answer is - only one string will be created, but two strings will exist. The "Shark"
String literal will be placed in the String Pool at compilation time, and the constructor invocation will create a new String object at runtime, which will not be in the string pool, but on the heap; and eligible for garbage collection when normal conditions are met.
Had we called .intern()
on it - new String("Shark").intern()
then the answer chanes to "only one string will be created, and only one string will exist. The .intern()
would return the reference to the "Shark" from the string pool, placed there at compilation time, and the string created by new String("Shark")
will be garbage collected since nothing is referencing it anymore.
Another example of a string pool question would be this:
String s1 = "Shark";
String s2 = "Shark";
String s3 = new String("Shark");
String s4 = new String("Shark").intern();
System.out.println("s1 == s2 :"+(s1==s2));
System.out.println("s1 == s3 :"+(s1==s3));
System.out.println("s1 == s4 :"+(s1==s4));
What will be printed out by this code snippet?
Which would of course, print out this:
s1 == s2 :true
s1 == s3 :false
s1 == s4 :true
For completeness, the above example will create exactly one string in the string pool, and one on the heap. One for the two identical "Shark"
literals - during compilation time, one on the heap for the new String("Shark")
instantiation, and the new String("Shark").intern()
will return a reference to the "Shark"
literal created at compilation time.
EVERY string literal will end up in the string pool. But your question, as posted, doesn't really have anything to do with the typical string pool questions.