java - String Pool - String Object - Garbage Collection -


confused how garbage collection works in below cases. considering below piece of code.

string s1 = "abc"; // s1 points "abc" string s2 = s1;   // s2 points "abc" string s3 = "abc1"; // s3 points "abc1"  s1 = s3; // s1 points "abc1" s2 = null;  // s2 reference removed, "abc" no longer referenced 

after this, "abc" eligible gc.

also if same above example, if use new string()

string s1 = new string("abc"); 

now result.

also there tools, through can monitor garbage collection, objects getting collected gc

string s1 = "abc"; // s1 points "abc" here, "abc" added string constants pool , usually not gced. string literal (within double quotes) usually not gced.

string s1 = new string("abc");

the above line creates 2 strings. "abc" added string constants pool (assuming not present there already) , string value "abc" on heap. string object present on heap can gced once becomes unreachable (i.e, there no references it)


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -