Which method can be used to set the length of the buffer within a StringBuffer object?

In this example, we will learn to clear the string buffer using the delete() and setLength() method and creating a new StringBuffer object in Java.

Example 1: Java program to clear using StringBuffer using delete()

class Main {
  public static void main(String[] args) {

    // create a string buffer
    StringBuffer str = new StringBuffer();

    // add string to string buffer
    str.append("Java");
    str.append(" is");
    str.append(" popular.");
    System.out.println("StringBuffer: " + str);

    // clear the string
    // using delete()
    str.delete(0, str.length());
    System.out.println("Updated StringBuffer: " + str);
  }
}

Output

StringBuffer: Java is popular.
Updated StringBuffer: 

In the above example, we have used the delete() method of the StringBuffer class to clear the string buffer.

Here, the delete() method removes all the characters within the specified index numbers.


Example 2: Clear the StringBuffer using setLength()

class Main {
  public static void main(String[] args) {

    // create a string buffer
    StringBuffer str = new StringBuffer();

    // add string to string buffer
    str.append("Java");
    str.append(" is");
    str.append(" awesome.");
    System.out.println("StringBuffer: " + str);

    // clear the string
    // using setLength()
    str.setLength(0);
    System.out.println("Updated StringBuffer: " + str);
  }
}

Output

StringBuffer: Java is awesome.
Updated StringBuffer

Here, the setLength() method changes the character sequences present in StringBuffer to a new character sequence. And, set the length of the new character sequence to 0.

Hence, the older character sequence is garbage collected.

Note: The setLength() method completely ignores the character sequence present in the string buffer. However, the delete() method accesses the character sequence and deletes it. Hence, setLength() is more faster than delete().


Example 3: Clear the StringBuffer by creating a new object

class Main {
  public static void main(String[] args) {

    // create a string buffer
    StringBuffer str = new StringBuffer();

    // add string to string buffer
    str.append("Java");
    str.append(" is");
    str.append(" awesome.");
    System.out.println("StringBuffer: " + str);

    // clear the string
    // using new
    // here new object is created and assigned to str
    str = new StringBuffer();
    System.out.println("Updated StringBuffer: " + str);
  }
}

Output

StringBuffer: Java is awesome.
Updated StringBuffer:

Here, new StringBuffer() creates a new string buffer object and assigns the previous variable to the new objects. In this case, the previous object will be there. But it won't be accessible so it will be garbage collected.

Since, every time instead of clearing the previous string buffer, a new string buffer is created. So it is less efficient in terms of performance.

StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.

StringBuffer may have characters and substrings inserted in the middle or appended to the end. It 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

StringBuffer( ): It reserves room for 16 characters without reallocation.

StringBuffer s=new StringBuffer();
StringBuffer( int size)It accepts an integer argument that explicitly sets the size of the buffer.

StringBuffer s=new StringBuffer(20);
StringBuffer(String str): It accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.

StringBuffer s=new StringBuffer("PrutordotAi");
Methods

Some of the most used methods are:

length( ) and capacity( ): The length of a StringBuffer can be found by the length( ) method, while the total allocated capacity can be found by the capacity( ) method.
Code Example:

import java.io.*;
class P_AI {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("PrutordotAi");
int p = s.length();
int q = s.capacity();
System.out.println("Length of string PrutordotAi=" + p);
System.out.println("Capacity of string PrutordotAi=" + q);
}
}
Output:
Length of string PrutordotAi=13
Capacity of string PrutordotAi=29
append( ): It is used to add text at the end of the existence text. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
Code Example:

import java.io.*;
class P_AI {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("prutordot");
s.append("Prutor");
System.out.println(s); // returns PrutordotAi
s.append(1);
System.out.println(s); // returns PrutordotAi1
}
}
Output:

PrutordotAi
PrutordotAi1

insert( ): It is used to insert text at the specified index position. These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object.

Code Example:

import java.io.*;
class P_AI {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("Prutor.Ai");
s.reverse();
System.out.println(s); // returns iA.roturP
}
}
Output:
iA.roturP
delete( ) and deleteCharAt( ): It can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ).The delete( ) method deletes a sequence of characters from the invoking object. Here, start Index specifies the index of the first character to remove, and end Index specifies an index one past the last character to remove. Thus, the substring deleted runs from start Index to endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
Code Example:

import java.io.*;
class P_AI {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("PrutordotAi");
s.delete(0, 5);
System.out.println(s); // returns Prutor
s.deleteCharAt(7);
System.out.println(s); // returns forPrutor
}
}
Output:
Prutor
forPrutor
replace( ): It can replace one set of characters with another set inside a StringBuffer object by calling replace( ). The substring being replaced is specified by the indexes start Index and endIndex. Thus, the substring at start Index through endIndex–1 is replaced. The replacement string is passed in str.The resulting StringBuffer object is returned.Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
Code Example:

import java.io.*;
class P_AI {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("PrutordotAi");
s.replace(5, 8, "are");
System.out.println(s); // returns PrutorarePrutor
}
}
Output:
PrutorarePrutor
ensureCapacity( ): It is used to increase the capacity of a StringBuffer object. The new capacity will be set to either the value we specify or twice the current capacity plus two (i.e. capacity+2), whichever is larger. Here, capacity specifies the size of the buffer.
void ensureCapacity(int capacity)
Besides that all the methods that are used in String class can also be used.

StringBuffer appendCodePoint(int codePoint): This method appends the string representation of the codePoint argument to this sequence.
Syntax:
public StringBuffer appendCodePoint(int codePoint)
char charAt(int index): This method returns the char value in this sequence at the specified index.
Syntax:
public char charAt(int index)
IntStream chars(): This method returns a stream of int zero-extending the char values from this sequence.
Syntax:
public IntStream chars()
int codePointAt(int index): This method returns the character (Unicode code point) at the specified index.
Syntax:
public int codePointAt(int index)
int codePointBefore(int index): This method returns the character (Unicode code point) before the specified index.
Syntax:
public int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex): This method returns the number of Unicode code points in the specified text range of this sequence.
Syntax:
public int codePointCount(int beginIndex,
int endIndex)
IntStream codePoints(): This method returns a stream of code point values from this sequence.
Syntax:
public IntStream codePoints()
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): In this method, the characters are copied from this sequence into the destination character array dst.
Syntax:
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
int indexOf(String str): This method returns the index within this string of the first occurrence of the specified substring.
Syntax:
public int indexOf(String str)

public int indexOf(String str,
int fromIndex)
int lastIndexOf(String str): This method returns the index within this string of the last occurrence of the specified substring.
Syntax:
public int lastIndexOf(String str)

public int lastIndexOf(String str,
int fromIndex)
int offsetByCodePoints(int index, int codePointOffset): This method returns the index within this sequence that is offset from the given index by codePointOffset code points.
Syntax:
public int offsetByCodePoints(int index,
int codePointOffset)
void setCharAt(int index, char ch): In this method, the character at the specified index is set to ch.
Syntax:
public void setCharAt(int index,
char ch)
void setLength(int newLength): This method sets the length of the character sequence.
Syntax:
public void setLength(int newLength)
CharSequence subSequence(int start, int end): This method returns a new character sequence that is a subsequence of this sequence.
Syntax:
public CharSequence subSequence(int start,
int end)
String substring(int start): This method returns a new String that contains a subsequence of characters currently contained in this character sequence.
Syntax:
public String substring(int start)

public String substring(int start,
int end)
String toString(): This method returns a string representing the data in this sequence.
Syntax:
public String toString()
void trimToSize(): This method attempts to reduce storage used for the character sequence.
Syntax:
public void trimToSize()
Some Interesting facts:

java.lang.StringBuffer extends (or inherits from) Object class.
All Implemented Interfaces of StringBuffer class:Serializable, Appendable, CharSequence.
public final class StringBuffer extends Object implements Serializable, CharSequence, Appendable
String buffers are safe for use by multiple threads. The methods can be synchronized wherever necessary so that all the operations on any particular instance behave as if they occur in some serial order.
Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source.
It inherits some of the methods from Object class which are clone, equals, finalize, getClass, hashCode, notify, notifyAll.

StringBuilder: J2SE 5 adds a new string class to Java’s already powerful string handling capabilities. This new class is called StringBuilder. It is identical to StringBuffer except for one important difference: it is not synchronized, which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which you are using multithreading, you must use StringBuffer rather than StringBuilder.

How do you measure the length of a StringBuffer?

To find the length of the StringBuffer object, the length() function is used. It is a method of the StringBuffer Class. The method returns the count of characters in the sequence.

Which method is used to set the size of the buffer in Java?

The limit() method of java. nio. Buffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit.

Which of these method of class StringBuffer is used to find the length?

Explanation: length() method is used to obtain length of StringBuffer object, length of “Hello” is 5. 7.

Which of these method of class StringBuffer is used to find the length of current character sequence?

length() method returns the length (character count) of the sequence of characters currently represented by this object.