Hi,
How stringbuffer implementation is being done in Java. I mean how it creates objects and appends values??
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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.