String Buffering
A string buffer is a string object or changeable character sequence. The string buffer default capacity is 16 characters. It contains synchronized methods which means thread-safe. There are various constructors:-
public StringBuffer();
public StringBuffer(int capacity);
public StringBuffer(String s);
1. length():- Find out the string's length.
Syntax:- public synchronized int length();
Example :- StringBuffer s1=new StringBuffer("hello");
System.out.println(s1.length()); =>5
2. capacity():- It is to find out the StringBuffer object's current capacity.
Syntax:- public synchronized int capacity();
Example:- StringBuffer b = new StringBuffer( );
System.out.println(“default Capacity”+ b.capacity()); =>16
3. append():- It is used to concatenate the given string with the given argument.
Syntax:-public synchronized StringBuffer append(primitive type)
Example:- StringBuffer b = new StringBuffer("Hi");
StringBuffer c= b.append("Indian");
System.out.println(b); //HiIndian
System.out.println(c); //HiIndian
4. insert():-Using this technique, a string may be inserted at a certain location.
Syntax:-public synchronized StringBuffer insert(int, String);
Example:- StringBuffer s=new StringBuffer("Hello");
s.insert(2,"india");
System.out.println(s); //Heindiallo
5. replace():- It is used to replace the given string from the specific position.
Syntax:- public synchronized StirngBuffer replace(int, int, String)
Example:- StringBuffer r=new StringBuffer("india");
r.replace(1,3,"Welcome to");
System.out.println(r); =>iWelcome toia
Code Example
class A
{
public static void main(String arr[])
{ A b = new A();
System.out.println("Default Capacity= "+ b.capacity());
b.append("hello i am indian.");
System.out.println("Capacity after append= "+ b.capacity());
System.out.println("capacity after append " +b);
}
}
RANREV INFOTECH