简体   繁体   中英

String immutability test

Consider the code

String s="hello";
s=s.concat("java");

As String objects are immutable so new object should be created with value “Hello Java” referenced by S.

Now my query is that where is that earlier String object “hello” referenced by s initially gone?

Does it still exist in memory? if so then how? because in Java the life time of object remains only till it's reference exist. In case of “hello” it's reference had lost when second statement executed. so how can it still exist in memory???

Please someone solve my doubt. :)

Does it still exist in memory?

Yes. The s variable just doesn't reference it any more.

It will continue to exist in the constant pool, since you have declared it as a string literal; even if it were not in the constant pool, it would continue to exist until it is garbage collected, which will not happen immediately.

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