When are constant Strings created/destroyed?
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(..){
Sy开发者_运维知识库stem.out.println(getString());}
}
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?
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?
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.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.
精彩评论