2

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?

remy
  • 1,255
  • 6
  • 20
  • 27
  • 2
    Just a comment for part 1, the compiler may optimise the second one into just `String b = "hello";`, so no guarantees there. – joshuahealy Apr 13 '12 at 04:06
  • 3
    @appclay The compiler is *required* to intern strings that are the values of constant-expressions, by http://docs.oracle.com/javase/specs/jls/se5.0/html/lexical.html#3.10.5. This is a guarantee. – user207421 Apr 13 '12 at 04:54
  • @EJP Learn something new every day... – joshuahealy Apr 13 '12 at 05:00

2 Answers2

4

3) readLine() won't use the value from the string pool. You would have to call intern() on it first.

line = br.readLine().intern();

From the String Javadoc:

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
2

AFAIk, these are the things happening:

1.when javac compiler encounters the above line, it will change it to StringBuffer like this:

String b = new StringBuffer().append("hell").append("o").toString();

String a will be in pool with the value "hello".

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()?

Community
  • 1
  • 1
UVM
  • 9,776
  • 6
  • 41
  • 66
  • 1
    for question 1, I don't understand why b is created by new stringBuffer. because if System.out.println(a==b), the result is true. So I think a and b refer to the same object "hello" in the pool. but if b is created by new stringBuffer, "hello" object will in the heap. – remy Apr 13 '12 at 05:25
  • this is how internally the java compiler retains the string,for more information you can visit this link.http://java.sun.com/docs/books/performance/1st_edition/html/JPMutability.fm.html#22028 – UVM Apr 13 '12 at 05:34