Monday, March 21, 2016

String vs. StringBuffer/StringBulider

Hi all,

In this post, I’ll demonstrate how memory behave while string type data involving scenario in our JAVA program. Basically, when we execute JAVA program on our PC, Java mange PCs main memory in its own way. For string type operations are handled through following 3type of memory segments.
  • Stack
  • Heap
  • Pool






String data type is immutable, mean when changes happen to literals particular literals never change, instead of that reference variable pointed to new value. This behavior helps to manage literals which have more than one reference.

When we consider above scenario, step 1 to 4 nameList variable reference to new literals in each step of the loop, at the same time previous values of literals are reaming inside the pool without any references, instead of JAVA garbage collector involving to clear pool, String pool will be full of garbage value.

For mitigate these kind of scenario JAVA 5 introduces StringBuffer & StringBulider both of the classes are not immutable. Let’s see how to implement above code segment using StringBuffer class.


Happy Coding,
Regards,
Denuwan Himanga

No comments:

Post a Comment