Originally posted by amarkirt saroay: How many String objects are created in the following code:
As per my understanding there will be 5 : "Basic","23","Basic23","Ba23","BA23". I am not considering s as a seaprate object as its just a eference(we did not do new String() for it) Is it correct?
The place where you saw a question like this asked how many string will be created when you invoke a method that executes this code. The answer there is 3. Because before invoking the method there will be 2 strings in the pool already. "Basic" and "23".
String literals are constants that are created when the class that constains them is loaded. The string objects exist on the heap like any object. They are referenced by the constant pool.
Note that this is only true if no string constant already exists with the same content (if class A causes "Hello" to be created and class B contains "Hello" as well, no new string object with content "Hello" is created if class B is loaded. Instead, both A and B will share).