×

StringBuffer in Java

StringBuffer in Java

Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe.


Java StringBuffer Constructor

The StringBuffer class has the following four constructors.

1) StringBuffer(): The parameter less constructor that creates an empty String Buffer and provides the initial size of the buffer for 16 characters.

2) StringBuffer(int s): It is a parameterized constructor that builds an empty String Builder and provides the initial size (s) of the buffer specified in the argument.

4) StringBuffer(String st): Another parametrized constructor that makes a non-empty String Buffer using the content provided in the argument. It also allocates space for 16 more characters.

Java Program

The following code uses the above-mentioned constructors to create objects of the StringBuffer class.

FileName: StringBufferExample.java

// A Java program to demonstrate StringBuffer

 import java.util.*;
public class StringBufferExample
{
// main method
public static void main(String argvs[]) throws Exception
{
// build a StringBuilder object
// using the parameterless constructor
StringBuffer sb = new StringBuffer();
int capacity = sb.capacity();
System.out.println("Capacity of the Buffer is = " + capacity);
// building a StringBuffer object
// using the StringBuffer(int s) constructor
StringBuilder sb1 = new StringBuilder(10);
// display string on the console
System.out.println("Capacity of the Buffer is = " + sb1.capacity());
String str = "Tutorial & Example";
// build a StringBuffer object
// using the StringBuffer(String) constructor
StringBuilder sb2 = new StringBuilder(str);
// display string on the console
System.out.println("The String is = " + sb2);
capacity = sb2.capacity();
System.out.println("Capacity of the Buffer is = " + capacity);
}
} 

Output:

 Capacity of the Buffer is = 16
Capacity of the Buffer is = 10
The String is = Tutorial & Example
Capacity of the Buffer is = 34 


Explanation: The last statement of the output shows the capacity as 34. The size of the string “Tutorial & Example” is 18, and room for 16 more characters is provided by the

 constructor making the total capacity as 18 + 16 = 34.

Java StringBuffer Class Methods
The StringBuffer class has a lot of inbuilt methods. A few of them are mentioned below.

Method NameDescription
public synchronized StringBuffer append(String str)Used to add string str at the end of the string on which the append() method is called. The append() method is overloaded with primitive data type like append(int), append(float), etc.
public synchronized StringBuffer replace(int start, int end, String s)Replaces the specified string from index start to index end using the string s.
public synchronized StringBuffer delete(int start, int end)Used to delete the character from the start index to the end index from the specified string.
public int capacity()Renders the capacity of the buffer
public synchronized StringBuffer reverse()Modifies the given string by reversing the order of its character
public void ensureCapacity(int capacity)Ensures that the minimum capacity of the buffer is always greater than or equal to the capacity specified in the parameter
public int length()Returns the total number of characters present in the string.
public String substring(int i)Return the substring whose ending is in the last character of the specified  substring, and the first character is the character positioned at the index i, which is mentioned in the argument.
public String substring(int sIndex, int eIndex)Returns the substring which starts from the index sIndex, and ends at eIndex.
public char charAt(int i)Returns the character present at the specified index i.


Let’s understand the methods one by one through Java programs.

The append() method

FileName: StringBufferMethodsExample.java

 public class StringBufferMethodsExample
{ 
    // main method
    public static void main(String argvs[])
    { 
        // creating an object of the String Buffer class
        StringBuffer sb = new StringBuffer("Hello World "); 
        System.out.println("String before the append method is invoked - " + sb);
        sb.append("New Java "); // adding the string “New Java” at the end of the string 
        System.out.println(); // new line
        System.out.println("String after the append method is invoked  - " + sb);
    } 
} 

Output:

String before the append method is invoked - Hello World
String after the append method is invoked  - Hello World New Java

Explanation: It is evident that the append() method inserts the specified string at the end of the given string.
The charAt() method
FileName: StringBufferMethodsExample1.java

public class StringBufferMethodsExample1
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer("Hello World "); 
    int i = 6; // i represents index
    // ch stores the character present at index i
    char ch  = sb.charAt(i);
    // displaying the character present at the index i
    System.out.println("Character present at the index " + i + " is " + ch);
} 
} 

Output:

Character present at the index 6 is W

Explanation: In the program, the variable ch stores the character present at the index i.

The replace() method

FileName: StringBufferMethodsExample2.java

 public class StringBufferMethodsExample2
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer("Hello World "); 
    System.out.println("The given string is " + sb);
    // starting and ending index
    int start = 9;
    int end = 11;
    // string that does the replacement
    String str = "zz";
    // invoking the replace() method
    StringBuffer newSb = sb.replace(start, end, str);
    System.out.println(); // new line
    System.out.println("The updated string is " + newSb);
}  
}  

Output:

 The given string is Hello World
The updated string is Hello Worzz 

Explanation: The replace() method considers the indices just before the end index, starting from the start index. Thus, as per the above program, the replace() method considers indices from 9  to (11 – 1), i.e., 9 to 10. Thus, characters ‘r’ and ‘l’ are omitted, and the output confirms the same.

The delete() method

FileName: StringBufferMethodsExample3.java

 public class StringBufferMethodsExample3
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Builder class
    StringBuffer sb = new StringBuffer("Hello World "); 
    System.out.println("The given string is " + sb);
    // specifying the starting and ending index
    int startIndex = 0;
    int endIndex = 4; // ennIndex – 1 will be considered.
    // invoking the delete() method
    StringBuffer newSb = sb.delete(startIndex, endIndex);
    System.out.println(); // new line
    System.out.println("The updated string is " + newSb);
} 
}  

Output:

 The given string is Hello World
The updated string is o World 

Explanation: Similar to the replace() method, the delete() method considers the index, which is just before the specified ending index as its last index (endIndex – 1 in our case). The start index is startIndex. Hence, the characters ‘H’, ‘e’, ‘l’, ‘l’  from the given string get erased, which is evident by looking at the output.

The capacity() method

FileName: StringBufferMethodsExample4.java

 public class StringBufferMethodsExample4
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer( );
    // invoking the method capacity
    int capacity = sb.capacity();
    System.out.println("The capacity of the buffer is: " + capacity);
} 
}  

Output:

The capacity of the buffer is: 16

Explanation: Similar to the StringBuilder class, in StringBuffer also, calling the parameter less constructor gives the buffer capacity 16.

The ensureCapacity() method

FileName: StringBufferMethodsExample5.java

 public class StringBufferMethodsExample5
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer( );
    int minCapacity = 40;
    // invoking the method ensureCapacity(), with minCapacity as its argument
    sb.ensureCapacity(minCapacity);
    // invoking the method capacity
    int capacity = sb.capacity();
    System.out.println("The current capacity of the buffer is: " + capacity);
} 
}  

Output:

The current capacity of the buffer is: 40

Explanation: In the above program, the ensureCapacity() method takes minCapacity as 40 in its argument. Therefore, the current buffer capacity has to be greater than or equal to the value fetched by the variable minCapacity.

The reverse() method

FileName: StringBufferMethodsExample6.java

 public class StringBufferMethodsExample6
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer("Hello World "); 
    System.out.println("The given string is " + sb);
    // invoking the reverse() method
    StringBuffer newSb = sb.reverse();
    System.out.println(); // new line
    System.out.println("The updated string is " + newSb);
} 
}  

Output:

 The given string is Hello World
The updated string is  dlroW olleH 

Explanation: In the program, the variable newSb stores the reversed string that is getting displayed in the output. The reverse() method comes in handy when one wants to check for palindromic strings.

The length() method

FileName: StringBufferMethodsExample7.java

 public class StringBufferMethodsExample7
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer("Hello World "); 
    System.out.println("The given string is " + sb);
    // invoking the length() method
    int length = sb.length();
    System.out.println(); // new line
    System.out.println("The length of the string is " + length);
} 
}  

Output:

 The given string is Hello World
The length of the string is 12 

Explanation: The length() method counts the total number of characters present in the input string.

The substring() method - I

FileName: StringBufferMethodsExample8.java

 public class StringBuilderMethodsExample8
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Builder class
    StringBuffer sb = new StringBuffer("Hello World In The String Buffer"); 
    System.out.println("The given string is " + sb);
    int index  = 6;
    // invoking the substring() method
    String newSb = sb.substring(index);
    System.out.println(); // new line
    System.out.println("The substring starting from index " + index + " is " + newSb);
} 
}  

Output:

 The given string is Hello World In The String Buffer
The substring starting from index 6 is World In The String Buffer 

Explanation: In the above program, we have only specified the starting index of the substring. The last index of the substring automatically becomes the last index of the given string.

The substring() method - II

FileName: StringBufferMethodsExample9.java

 public class StringBufferMethodsExample9
{ 
// main method
public static void main(String argvs[])
{ 
    // creating an object of the String Buffer class
    StringBuffer sb = new StringBuffer("Hello World In The String Buffer"); 
    System.out.println("The given string is " + sb);
    int startIndex  = 6;
    int endIndex = 9;
    // invoking the substring() method
    String newSb = sb.substring(startIndex, endIndex);
    System.out.println(); // new line
    System.out.println("The substring starting from index "  + startIndex + " and ending at " + endIndex + " is " + newSb);
} 
}  

Output:

 The given string is Hello World In The String Buffer
The substring starting from index 6 and ending at 9 is Wor 

Explanation: The substring() method used in the above program is another version that requires the ending index too. Thus, whatever is present between the starting and ending index gets printed on the console. Note that the starting and the ending index have to be within the range of the input string; otherwise, the StringIndexOutOfBoundsException is raised.


Related Topics

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.