I know that String a = “hello”; will put the “hello” into string literal pool. my question is:
1.
String a = "hello";
String b = "hell"+"o";
Does the string literal pool has three object: “hello”, “hell”, and “o”?
2.
String a = "hello";
String b = new String("hello");
then there will be a “hello” object in string literal pool and a string object in heap?
3.
BufferedReader br = new BufferedReader(new FileReader("names"));
String line = br.readLine(); //(the value of line is "hello" now, for example)
then there will be a “hello” object in string literal pool and a string object in heap?
AFAIk, these are the things happening:
1.when javac compiler encounters the above line, it will change it to
StringBufferlike this:2
String b will in the heap.3.This is purely an in memory operation as it is loading the file contents dynamically.Java compiler never
get a chance to know its memory structure because it is depending on the file size now.So it cannot be pooled.But when you perform a intern() these are the things happening:
If you call a string with method intern(), it is definitely garbage collected in modern JVMS.
It can be used to save memory if many string with the same content.
There is a nice discussion about this here:
Is it good practice to use java.lang.String.intern()?