Working with StringBuffer class

Working with StringBuffer class


Posted in : Core Java Posted on : October 15, 2010 at 3:56 PM Comments : [ 0 ]

This section contains the detail about the StringBuffer classs in java.

Working with StringBuffer class

The string object can't be altered once it was created . Java has a peer class of String, called StringBuffer, which allows strings to be altered. StringBuffer may have characters and substrings inserted in the middle or appended to the end.

Following are some of the key methods of it :

    Methods            Description         
length() Finds the current length of  a StringBuffer.
capacity() Returns the total allocated capacity.
ensureCapacity() Sets the size of the buffer.
setLength() Sets the length of the buffer within a StringBuffer.
charAt() Returns value of a single character at provided index.
setCharAt() Sets the value of a character at provided index.
getChars() It copies a substring of a StringBuffer into an array.
append() It concatenates the string  at the end of the invoking
String Buffer object
insert() It inserts one string into another at the specified index.
reverse() It reverses the characters within a StringBuffer object.
delete() Delete characters within a StringBuffer specified by
the indexes.
deleteCharAt() Delete the character at the index specified.
replace() Replaces one set of characters with another set inside
a StrignBuffer object, specified  by the indexes .
substring() Obtains a portion of a StringBuffer specified by the indexes.

Examples :

append() :


public class AppendStringDemo {
	public static void main(String args[]) {
		String s;
		int x = 12;
		StringBuffer strb = new StringBuffer(40);
		s = strb.append("x=").append(x).append("!").toString();
		System.out.println(s);
	}

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac AppendStringDemo.java

C:\Program Files\Java\jdk1.6.0_18\bin>java AppendStringDemo
x=12!

insert()


public class InsertStringDemo {
	public static void main(String args[]) {
		StringBuffer strb = new StringBuffer("I Devmanuals! ");

		strb.insert(2, "like ");
		System.out.println(strb);
	}

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac InsertStringDemo.java

C:\Program Files\Java\jdk1.6.0_18\bin>java InsertStringDemo
I like Devmanuals!

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics