1

Hi i am working in java and want to know how String objects are created in the String pool and how they are managed.

So in the following example i am creating two Strings s and s1,so can anyone explain me how many Objects are created in LIne1?Also how many Objects are eligible for garbage collection in Line3?

  String s = "x" + "y";//Line 1
  String s1 = s;//Line 2
  s = null;//Line 3

2 Answers 2

3

Only one object is created "xy" . compiler does it for optimization.

No object is eligible for garbage collection.

Sign up to request clarification or add additional context in comments.

3 Comments

So Objects "x" and "y" will not get created in the pool?My understanding is(which might be wrong) three object will be created.
@JavaGeek That will only happen if you force it to create a new object, with new String(string)
No. Concatenation of many literals in single line will create single object. Compiler generates such optimized code which will end up with single object.
0

It would create one object xy in the String constant pool area. As "x"+"y" would be evaluated during compilation. Additionally, garbage collector cannot access String constant pool area.

Reference: https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.