StringBuffer

  • As we know we can't modify a String which is immutable means fixed length to allow this we are using StringBuffer where we can modify a String .
  • StringBuffer represents growable and writable character sequences.

  • StringBuffer may have characters and substrings inserted in the middle or appended to the end.

  • StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.

StringBuffer Constructors

  • It defines four constructors as follows

StringBuffer( ) //reserves room for 16 characters without reallocation.

StringBuffer(int size) //explicitly sets the size of a buffer with the integer value of size.

StringBuffer(String str) //sets StringBuffer object with the str as initial value and reserves room for 16 more characters without reallocation

StringBuffer(CharSequence chars) //set the object with the character sequence contained in chars and reserves room for 16 more characters

length( ) and capacity( )

length( )

  • The current length of a StringBuffer can be obtain by length() method with the following general form.

int length( )

capacity( )

  • It returns the total allocated capacity of the StringBuffer by using the following general form.

int capacity( )

// StringBuffer length vs. capacity.
class StringBufferDemo {
 public static void main(String args[]) {
 StringBuffer sb = new StringBuffer("Hello");
 System.out.println("buffer = " + sb);
 System.out.println("length = " + sb.length());
 System.out.println("capacity = " + sb.capacity()); //21 because room for 16 additionally length is added
 }
}

Output:

buffer = Hello
length = 5
capacity = 21

ensureCapacity( )

  • It is used to preallocate room for a certain number of characters after a StringBuffer has been constructed.
  • It is useful when we know already that we will append a large length of stings in to a StringBuffer.
  • It's general form is:

void ensureCapacity(int minCapacity)

  • minCapacity specifies the minimum size of the buffer.
// StringBuffer ensureCapacity()
public class StringBufferDemo2 
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("Hello");
 sb.ensureCapacity(22);
 System.out.println("capacity = " + sb.capacity());
  }
}

Output:

capacity = 44

setLength( )

  • It is used to set the length of the string within a StringBuffer object.
  • Its general form is as follows:

void setLength(int len)

  • len specifies the length of the string which must be a non-negative value.

  • When we increase the size of the string,null characters are added to the end.

  • If the setLength( )with a value less than the current value returned by length( ),then the characters stored beyond the new length will be lost.

// StringBuffer length vs. capacity.
public class SetLengthDemo
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("Hello");
 sb.setLength(10);
 System.out.println("length = " + sb.length());
 System.out.println("buffer = " +sb);

   sb.setLength(3);
   System.out.println("length= "+sb.length());
   System.out.println("buffer = " +sb);  //characters will be lost as its length is decreased 
 }
}

Output:

length = 10
buffer = Hello
length= 3
buffer = Hel

charAt( ) and setCharAt( )

charAt( )

  • We can obtain the value of a single character from a StringBuffer by using following general form::

char charAt(int where)

setCharAt( )

  • This allows us to set the value of a character within the StringBuffer by using following general form::

void setCharAt(int where, char ch)

  • where specifies the index of the character which we want to perform action.
  • ch specifies the character that have to be set in the place of specified character in StringBuffer.
// Demonstrate charAt() and setCharAt().
public class setCharAtDemo
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("Hello");
 System.out.println("buffer before = " + sb);
 System.out.println("charAt(1) before = " + sb.charAt(1));

   sb.setCharAt(1, 'i');

 System.out.println("buffer after set a character = " + sb);
 System.out.println("charAt(1) after = " + sb.charAt(1));
 }
}

Output:

buffer before = Hello
charAt(1) before = e
buffer after set a character = Hillo
charAt(1) after = i

getChars( )

  • It is used to copy the String in StringBuffer in to an array by the following general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

  • sourceStart specifies the index of the beginning of the substring.

  • sourceEnd specifies an indexthat is one past the end of the desired substring.

  • subString contains the characters frrom sourceStart to sourceEnd-1.

  • target is the array which specifies the received characters.

  • targetStart specifies the index within target at which the substring will be copied.

//example for getChars()

public class GetChartsDemo
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("Hello World, Welcome");
   char ch[]=new char[10];
   sb.getChars(5,13,ch,0);
  System.out.println(ch);
 }
}

Output:

World,

append( )

  • The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object.

  • It have several overloaded functions as follows

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obj)

// Demonstrate append().
public class appendDemo 
{
 public static void main(String args[]) 
 {
 String s;
 int a = 42;
 StringBuffer sb = new StringBuffer(40);
 s = sb.append("a = ").append(a).append("!").toString();
 System.out.println(s);
 }
}

Output:

a = 42!

insert( )

  • It inserts one string into another.

  • It is overloaded to accept values of all the primitive types,Strings,Objects, and CharSequences.

StringBuffer insert(int index, String str)

StringBuffer insert(int index, char ch)

StringBuffer insert(int index, Object obj)

  • index specifies the index at which point the string will be inserted into the invoking StringBuffer object.
// Demonstrate insert().
public class insertDemo
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("I Java!");
   sb.insert(2, "like ");
 System.out.println(sb);
   sb.insert(0,'*');
  System.out.println(sb);
  }
}

Output:

I like Java!
*I like Java!

reverse( )

  • It will reverse the characters in a StringBuffer by using the following general form::.

StringBuffer reverse( )

  • It returns the reverse of the StrinBuffer on which it is called.
// Using reverse() to reverse a StringBuffer.
public class ReverseDemo 
{
   public static void main(String args[]) 
 {
 StringBuffer s = new StringBuffer("hello");
 System.out.println(s);
 s.reverse();
 System.out.println(s);
 }
}

Output:

hello
olleh

delete( ) and deleteCharAt( )

  • These methods are used to delete a character from a StringBuffer which have the following general forms::

    StringBuffer delete(int startIndex, int endIndex)//delete a sequence of characters from an invoking object

  • startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove means the substring deleted runs from startIndex to endIndex–1.

StringBuffer deleteCharAt(int loc) //deletes the character at index specified by loc.

// Demonstrate delete() and deleteCharAt()
public class deleteDemo 
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("This is a test.");
   sb.delete(4, 7);
 System.out.println("After delete: " + sb);
 sb.deleteCharAt(0);
 System.out.println("After deleteCharAt: " + sb);
 }
}

Output:

After delete: This a test.

After deleteCharAt: his a test.

replace( )

  • It is used to replace a one set of characters with another set within a StringBuffer by the followinggeneral form::.

StringBuffer replace(int startIndex, int endIndex, String str)

  • startIndex and endIndex specifies the substring to be replaced.

  • The replacement string is passed in str.

// Demonstrate replace()
public class replaceDemo
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("This is a test.");
 sb.replace(5, 7, "was");
 System.out.println("After replace: " + sb);
 }
}

Output:

After replace: This was a test.

substring( )

  • We can obtain a portion of a StringBuffer by using subString() method which have the following two forms::

    String substring(int startIndex) //returns the string that starts at index specified by startindex and to the end of the stringBuffer.

String substring(int startIndex, int endIndex)//returns the string specified by startIndex and endIndex

// Demonstrate substring()
public class replaceDemo
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("This is a test.");

 System.out.println("Substring(5): " + sb.substring(5));

 System.out.println("Substring(0,8):"+sb.substring(0,6)); //means 0 -5(6-1)

 }
}

Output:

Substring(5): is a test.
Substring(0,8):This i

Additional StringBuffer Methods

  • StringBuffer provides several additional methods as follows::
//example for indexOf and lastIndexOf()
public class IndexOfDemo 
{
 public static void main(String args[]) 
 {
 StringBuffer sb = new StringBuffer("one two one");
 int i;
 i = sb.indexOf("one");
 System.out.println("First index: " + i);
 i = sb.lastIndexOf("one");
 System.out.println("Last index: " + i);
 }
}

Output:

First index: 0
Last index: 8

StringBuilder

  • This is introduced by JDK5, which is a relatively recent addition to Java’s string handling capabilities.
  • StringBuilder is similar to StringBuffer except it is not synchronized, which means that it is not thread-safe.

  • The advantage of StringBuilder is faster performance.

  • As a mutable string will be accessed by multiple threads, and no external synchronization is employed, we must use StringBuffer rather than StringBuilder.

results matching ""

    No results matching ""