String creates a string of fixed length, while StringBuffer creates a string of flexible length, that can be modified in term of both length and contents. We can insert characters, sub-string in the middle or in the end of the StringBuffer.
Syntax: In Java, StringBuffer can be declared as follows:
StringBuffer sb = new StringBuffer("Java Programming");
The Java StringBuffer class defines a number of methods that allow us to manipulate a string.
S.No. | Method | Syntax | Description |
---|---|---|---|
insert() | s1.insert(n,s2) | Insert string s2 at n position in s1. | |
append() | s1.append('x') | Add any character or string at end of s1. | |
charAt() | s1.charAt(6) | Return the 6+1th character from s1. | |
subString() | s1.subString(6) s1.subString(n,m) | Return sub-string, starting from 6th character to end. It will work on both String as well as StringBuffer. Also, we can specify starting (n) to end (m) position. | |
indexOf() | s1.indexOf('x') | Return the index number of x character in s1. | |
indexOf() | s1.indexOf('x', n) | Return the index number of x character in s1 starting from nth position. | |
setLength() | s1.setLength(n) | Sets the length limit of string s1 to n. If n>s1.length() than spaces are added. | |
reverse() | s.reverse() | Reverse the characters stored in StringBuffer. | |
replace() | s.replace(5,7,"was") | Replace character at position 5, 6th index and insert "was" in it. | |
delete() | s.delete(4,7) | Delete characters on 4, 5 and 6th index. | |
deleteCharAt() | s.deleteCharAt(0) | It delete a single specified character. |