StringBuffer

597 views.


StringBuffer is a predefined class, used for storing group of characters. StringBuffer object can be created in only way and that is by using new operator.

Syntax:

StringBuffer sb=new StringBuffer(“Welcome”);

The StringBuffer objects are mutable which means we can modify the content of the object.

Example

StringBuffer sb=new StringBuffer(“hai”);

sb=new StringBuffer(“bye”);

 

Methods of StringBuffer:

1)int length():

This method will return the count of the number of characters available in StringBuffer.

Example:

StringBuffer sb=new StringBuffer(“Welcome”);

System.out.println(sb);

System.out.println(sb.length());

2)StringBuffer append(XXXX):

This method can be used to append the specified content to the existing StringBuffer object.

 

Example:

StringBuffer sb=new StringBuffer(“Welcome”);

System.out.println(sb.append(1.7);

System.out.println(sb.append(“Good Morning”));

3)StringBuffer deleteCharAt(int index):

This method can be used to delete a character that is available specified index position.

4)StringBuffer delete(int index, int offset):

This method can be used to delete a group of character beginning with specified index position up to the specified offset.

 

Example:

StringBuffer sb=new StringBuffer(“Welcome1.7Good Morning”);

System.out.println(sb.deleteChatAt(5);

System.out.println(sb.delete(3,10));

5) String subString(int index):

This method can be used to retrieve a part of StringBuffer beginning from the specified index position up to the end of the StringBuffer.

6)String subString(int index, int offset):

This method can be used to retrieve a part of the StringBuffer from the specified index position up to the specified offset.

Note:

The substring() will not modify the content of the StringBuffer

Example

StringBuffer sb=new StringBuffer(“Welcome1.7Good Morning”);

System.out.println(sb.subString(5);

System.out.println(sb.subString(3,10));

7) StringBuffer insert(int index, xxx):

This method can be used to insert the specified content at the specified index position.

Example

StringBuffer sb=new StringBuffer(“Welcome1.7Good Morning”);

System.out.println(sb.insert(0,”welcome”);

System.out.println(sb.delete(7,1.7));

8) StringBuffer replace(int index, int offset, String):

This method can be used to replace a group of characters beginning with the specified index position up to the specified offset, with the specified String.

Example

StringBuffer sb=new StringBuffer(“Welcome1.7Good Morning”);

System.out.println(sb.replace(0.7,”wel”);

9)StringBuffer reverse():

This method can be used to reverse the contents of StringBuffer.

Example

StringBuffer sb=new StringBuffer(“Welcome1.7Good Morning”);

System.out.println(sb.reverse();

 

Example:

Output:

P

 

 

 

 

 

Leave a Reply