String buffer class: The String class represents the fixed length String objects. The “String Buffer” class is a peer(superior) class of the String class. It represents writable and growable character sequences. Moreover you can have tent inserted in the middle, appended at the end or you can have a range of character deleted.
Constructors:
String Buffer(); The default constructor resumes room for 16 characters.
String Buffer(int size); This constructor resumes room for the specified number of characters in the buffer.
String Buffer(String s); Constructs a string buffer object from the content of string object.
- int length(); Returns the length of the string length object.
- int capacity(); Returns the capacity of the string buffer object.
import java.lang.*;
class App45
{
public static void main(String yck[])
{
StringBuffer b1=new StringBuffer();
System.out.println(b1.length());
System.out.println(b1.capacity());
StringBuffer b2=new StringBuffer(32);
System.out.println(b2.length());
System.out.println(b2.capacity());
StringBuffer b3=new StringBuffer("Chaitanya");
System.out.println(b3.length());
System.out.println(b3.capacity());
}
}
output:
\>javac App45.java
\>java App45
0
16
0
32
9
25
- String append(int num);
- String append(object obj);
- String append(String str); Appends the contents of an integer, another object or a String object into the invoking string buffer object.
import java.lang.*;
class App46
{
public static void main(String yck[])
{
StringBuffer b=new StringBuffer();
b.append("Hellow Chaitanya \n");
b.append("How is the life!");
System.out.println(b);
}
}
output:
\>javac App46.java
\>java App46
Hellow Chaitanya
How is the life!
- String insert(int index, int num);
- String insert(int index, object obj);
- String insert(int index, String str); Insert the contents of a number, a string object or another object at the specified index in the invoking String object.
import java.lang.*;
class App47
{
public static void main(String yck[])
{
StringBuffer b=new StringBuffer("I Java");
String s=new String("like ");
b.insert(2,s);
System.out.println(b);
}
}
output:
\>javac App47.java
\>java App47
I like Java
- StringBuffer deleteCharAt(int index); Deletes the character at the specified index.
- StringBuffer delete(int startindex, int endindex); Deletes a range of characters.
import java.lang.*;
class App48
{
public static void main(String yck[])
{
StringBuffer b=new StringBuffer("Chaitanya");
b.deleteCharAt(3);
System.out.println(b);
b.delete(2,4);
System.out.println(b);
String s=new String("like ");
}
}
output:
\>javac App48.java
\>java App48
Chatanya
Chanya
StringBuffer reverse(); Reverse the contents of a String Buffer object.
import java.lang.*;
class App49
{
public static void main(String yck[])
{
StringBuffer b=new StringBuffer("Chaitanya");
b.reverse();
System.out.println(b);
}
}
output:
\>javac App49.java
\>java App49
aynatiahC
