0

On some blog and site even on stack overflow, I can see similar ans for below question

    String s = new String("Test");

Will create two object as literal "Test" will take place in pool.

So how StringBuffer perform in below case.

    StringBuffer sb = new StringBuffer("BufferTest");

Is the literal "BufferTest" also take place in pool ?

if yes then how StringBuffer save String garbage collection ?

Amit
  • 497
  • 3
  • 8
  • 24
  • Have a look at this as well :- http://stackoverflow.com/questions/2909848/how-does-java-implement-flyweight-pattern-for-string-under-the-hood – Goyal Vicky Aug 15 '15 at 15:28

2 Answers2

0

"BufferTest" will take place in the pool because any String object does that.

spongebob
  • 8,370
  • 15
  • 50
  • 83
0

Is the literal "BufferTest" also take place in pool ?

Yes.

All literal strings are help in the string pool/

if yes then how StringBuffer save String garbage collection ?

It doesn't need to. A String corresponding to a string literal remains reachable so long as the class (or classes) that defined it is in existence / loaded.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • But As per below code I think with every append call StringBuffer loosing reference of first.
    ' StringBuffer sb = new StringBuffer();' ' sb.append("Test");' ' System.out.println(sb.toString());' sb.append("Test1"); System.out.println(sb.toString());
    – Amit Aug 15 '15 at 17:21
  • Like I said, the `StringBuffer` doesn't need to keep a reference to it. The reference for `"Test"` is placed in the string pool when the code is loaded, not when it is executed. – Stephen C Aug 15 '15 at 18:17