Hi,
How stringbuffer implementation is being done in Java. I mean how it creates objects and appends values??
Printable View
Hi,
How stringbuffer implementation is being done in Java. I mean how it creates objects and appends values??
Basically the same way an Vector<Char> is implemented. It allocates more space than it thinks is necessary, then it can simply "add" items by filling in those spaces. If it reaches the limit of spaces it has available, it will create a new larger allocated area, then copy over all the old values and unallocate the old area.
I don't use StringBuffer very often, though. More often I use the StringBuilder class which has exactly the same concept but it has no built-in thread safety, thus is much faster (same reason I don't use Vector very often but instead use ArrayList).
Go straight to the source (pun intended): java.lang: StringBuffer.java
Lets say StringBuffer sf = new StringBuffer("Hello");
then i would append "Hi" to my stringbuffer object. I am looking for an algorythm how java searches for that Hello obj and appends the value Hi to it?
I'm not sure what you're looking for... Java doesn't search for the hello obj (there isn't one), but rather looks for sf (if you're interested in how it does this, you'll need to delve into the memory model of the JVM). That object will have a field denoting the size of the current buffer and it's capacity. It will make a check to see if the value you're trying to append will overflow the buffer capacity. If it does, it re-allocates a bigger buffer and copies all current valid characters to the new buffer. Then it copies the values from what you're appending into buffer[size] to buffer[size+length(appending)] and updates the size field.
Thank u.. u answered my qn.