简体   繁体   中英

How String pool manages references if we change string value?

If we have a String s = "Hello" It will create string "Hello" in string pool and some reference is pointing to string s what if I change s="World" .In string pool it will create new String "World" and now my reference is pointing to World. What will happen to "Hello" String?

From the documentation of String :

... String objects are immutable ...

String -constants known at compile-time are also treated specially. They are stored in a constant pool. All "equal" compile-time String -constant reference the same String -object. This is the reason why

String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2);

will print true . There are some other interesting examples. I wrote an Ideone example a while back that demonstrates some of those interesting cases.

When one re-assings a value to some non-primitive type variable s , the old object still exists on the heap (as long as the Garbage Collector does not deem it eligible for collection). What is changed is where the variable s is referencing. In the case presented, a second String -constant is created at compile-time and s then references the second constant.

String objects are immutable, so what happens with your second assignment is only an object reference update.

String literal objects (like "Hello" and "World") will be referenced from Java's String pool (they are interned). As this counts as a reference, the "Hello" object will not be garbage collected after your reassignment. That will only happen if the code itself becomes unreachable (eg if the entire class was loaded dynamically and its class loader becomes now unreachable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM