String
and StringBuffer are two classes which extensively used in Java. As String is
final in Java so it is immutable and once created cannot be changed whereas
StringBuffer class is a mutable class. At a time String cannot be used by two
threads.
Example :
String
Str = “Hello”;
Then
we concat a string value to the same string variable.
Str
= Str + ” Friend”;
When
the value of 'Str' printed we get 'Hello Friends' but even we used same
variable but a new object was created in the process when the "Hello" string still exists but we
lost the reference to it.
StringBuffer
is mutable and one can change the value of the object because it is stored in
the heap.
append()
- Use for concatenation. Apart from a String, other data type also can be
concatnate with StringBuffer. Also used for Array of characters.
Example:
String
Buffer Sb=new StringBuffer("Test");
SB=SB.append("
Over");
int
x=10;
SB=SB.append(x);
List of StringBuffer class:
methods
capacity()
|
Returns the current
capacity.
|
charAt(int)
|
Same as
String.charAt(int)
|
delete(int Pos1,
int Pos2)
|
Removes characters
between given two points.
|
insert(int, String)
|
Insert a string at 's'
position. This method can be applied for other data type too.
|
lastIndexOf(String)
|
Same as String.
|
replace(int, int,
String)
|
Replace characters
in a substring given String.
|
reverse()
|
Reverse the given
String.
|
setCharAt(int,
char)
|
Replace the
character at the specified position with ch.
|
substring(int int)
|
Same as String.
|
substring(int)
|
Same as String.
|
indexOf(String)
|
Same as String.
|
indexOf(Stringr,
int)
|
Same as String.
|
lastIndexOf(String,
int)
|
Same as String.
|
length()
|
Same as String.
|
toString()
|
Same as String.
|
Some other
Methods -
setLength(int
newLength), subSequence(int, int), codePointAt(int), ensureCapacity(int), getChars(int, int,
char[], int), setLength(int), subSequence(int ,int), trimToSize()
StringBuilder
StringBuilder
class too represents string objects and like StringBuffer it can be changed.
StringBuilder also contains methods such as append, insert and can be use like
one we have seen in StringBuffer. At the basic difference is the StringBuilder
is faster than StringBuffer.
Almost
all methods that used in StringBuufer can be used in StringBuilder too.
Example
:
StringBuilder str = new
StringBuilder("Life is ");
str = str.append(" is beautiful");
Now,
it up to you, how you use your string.
No comments:
Post a Comment