Java – StringBuffer

Java – StringBuffer 2017-06-13T01:24:32+00:00

StringBuffer class :

StringBuffer is a peer class of String. String creates strings of fixed length, while StringBuffer creates strings of flexible length that can be modified in terms of both length and content.

So Strings that need modification are handled by StringBuffer class.

We can insert characters and substrings in the middle of a string, or append another string to the end.

StringBufer defines these Constructor:

StringBuffer()

StringBuffer(int size)

StringBuffer(String str)

 

Method Call Task Performed
Sb.length() Gives the current length of a StringBuffer.
Sb.capacity() Gives the total allocated capacity (default 16)
setLength(int len) Set the length of the buffer within a String Buffer object.
charAt(int where) Gives the value of character
setCharAt(int where, char ch) Set the value of a character within a StringBuffer.
S1.append(s2) Appends the string s2 to s1 at the end
S1.insert(n,s2) Inserts the string s2 at the position n of the string s1
S1.reverse() Reverse the string of s1
S1.deleteCharAt(nth) Delete the nth character of string s1
S1.delete(StartIndex, endIndex) Delete characters from start to end.

EX :

 


Output :
s1 =
s2 = Bhagirath
s3 = Bhagirath
s1.length = 0
s2.length = 9
s3.length = 9
s4.length = 0
s1.capacity = 16
s2.capacity = 25
s3.capacity = 25
s4.capacity = 100

EX :


 


Output :
s1 = Java2all
Deleting 5 to 8 character = Java2

EX :

 

 


Output :
s = Hello world!
s.length() = 12
s.length() = 28
Hello
s.length() = 5
s.length() = 28

Prev Next