简体   繁体   中英

String Literal Pool

Well, I've got such a code

String s = "hello";
String s2 = s + "world";

I know that variable s is stored in Java Heap in String Literal Pool. Also I know that variable s2 is stored in Java Heap (because '+' in this example creates a new object). But my question is: will "world" be put into Pool or nothing will happen with it?

Yes it will. Wherever / Whenever , you have a String literal declared, it goes to pool obviously, regardless the usage of it.

Since the String "world" does not exist in the pool, a new String object instantiates, then it is placed in the pool.

When we use double quotes to create a String , it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference.

Basically, 's' and 's2' are just references while real objects are "Hello" and "world". This follows the concept specifying Strings are immutable while String references are not. So, Yes, as "world" is String object,apart from being a String literal, it will be stored in heap similar to hello. Also remember neither 's' nor 's2' will goto heap as being mutable String references.

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