views:

72

answers:

1

Consider the following code

public static void method(String[] srgs){  
try{  

}catch(){  
System.out.println("Hello World" + "one");}  
catch(..){  
System.out.println("Hello World" + "two");}
catch(..){  
System.out.println(getString());}
}
  1. When are these Strings created? I assume the Strings will get created when an Exception occurs at run time. The string gets created at run time and is displayed. A peer of mine tells me that since these are constant Strings they will get created as soon as the Class loads. Is that correct?

  2. When are the Strings garbage collected? Are they garbage collected at all ? Assuming the same method may get called many times in the programs life time does it not make sense to just cache them?

+3  A: 
  1. These String are in fact constant String and will be in the constant pool of the class and thus will be instantiated in the JVM when the class is loaded. The fact that they are created with + doesn't matter, as the entire String is still a constant expression (i.e. it would be exactly the same as if you wrote "Hello Worldone" and "Hello Worldtwo"). These rules are described in § 3.10.5 String Literals of the JLS.

  2. String objects are garbage collected the same way any other object is garbage collected, there's nothing inherently different about them. However some String are interned (most notably this includes all string literals), which may or may not prevent them from being garbage collected (that's not defined and is implementation-dependent).

    So as long as your class remains loaded, those String constants will remain in existence and will not be garbage collected.

Joachim Sauer
Thanks Joachim, consider SOP("Hello World"+getstr()), in this case is the constant String still created ? When this line is executed is a 2nd String created ? Is the 2nd String Garbage collected ? Can you please give me a source from where you answered point 1.
Geek
I linked the relevant section of the JLS. `"HelloWorld" + getstr()` is **not** a `String` literal ('though it *contains* one: `"Hello World"`). A new `String` object is produced each time that line is executed and that object is garbage collected normally.
Joachim Sauer