StringBuffer class in Java
In the previous blog, we learned about the methods of String. If you want to know more about the methods of String, then visit String Methods in Java - Part 2. In this blog, we will learn about the StringBuffer class, its methods, etc. In general, StringBuffer works the same way String works but only the difference it is mutable (the contents of StringBuffer can be changed). In StringBuffer characters and substrings can be inserted in the middle or appended to the end. Now we will go through its Constructors and Methods.
Constructors
Creates an empty String Buffer containing the initial capacity of 16.
Creates String Buffer with the specified string
Creates an empty String Buffer with the specified length mentioned as capacity
Methods of StringBuffer Class
append()
append() is used for concatenating the specified string with the given string. It can even concatenate int, float, char, etc.
Syntax
e.g
Output
insert()
insert() is used when we want to insert a particular string at the specified location. We can also insert different types of values like int, float, char, double, etc.
Syntax
e.g
Output
replace()
replace() replaces the specified string with the particular start index and end index.
Syntax
e.g
Output
delete()
delete() is used for deleting the string from the given start index and end index.
Syntax
e.g
Output
reverse()
reverse() is used for reversing the current String.
Syntax
e.g
Output
Difference between String and StringBuffer Class
Features | String | StringBuffer |
---|---|---|
Mutable | String is immutable | StringBuffer is mutable |
Storage | String uses constant pool | StringBuffer uses heap memory |
Performance | String is slow during concatenation | StringBuffer is fast during concatenation |
Memory | String requires more memory compared to StringBuffer | StringBuffer requires less memory as compared to String |
Overrides Method | String overrides equal() method of Object class | StringBuffer doesn't override equal() of the Object class |