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());}
}
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?
Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.
26) In which memory a String is stored, when we create a string using new operator? Explanation: When a String is created using a new operator, it always created in the heap memory.
The String constant pool is a special memory area. When we declare a String literal, the JVM creates the object in the pool and stores its reference on the stack. Before creating each String object in memory, the JVM performs some steps to decrease the memory overhead.
Since, strings are immutable, they are reusable so they are pooled in the string literal pool by the JVM. And this is the recommended way, because you are reusing it. String message = new String("Hai");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With