StringBuffer In Java: 11 Popular Methods Every Java Developer Should Know

Introduction to StringBuffer in Java

StringBuffer in java is a class that inherits methods from java.lang.Object class. It is a peer class of String that is used to create modifiable or mutable String. It provides much of String’s functionality except that it can be changed, i.e., it represents writable and growable character sequences instead of immutable and fixed-length character sequences. Here are some essential points about the java.lang.StringBuffer in Java:

·  The content and length of the sequence of characters can be changed through various method calls.

·  It is thread-safe, i.e., safe for use by multiple threads

·   Every StringBuffer in java has a capacity.

·  The substrings and characters can be appended in the end or inserted in the middle. It automatically grows and makes room for additions. Often, more characters are preallocated than needed to allow room for growth.

Here is how the StringBuffer in the Java class is declared:

public final class StringBuffer

extends Object

implements Serializable, CharSequence

Constructors of StringBuffer Class

1. StringBuffer() – This is used to construct a string buffer with an initial capacity of 16 characters and no characters in it. Syntax:

StringBuffer a =new StringBuffer();

2. StringBuffer (CharSequence seq) – This is used to construct a string buffer that contains the same characters as in the CharSequence.

3. StringBuffer (int capacity) – This is used to create a string buffer whose initial capacity is specified and with no characters. Syntax:

StringBuffer a=new StringBuffer(10);

4. StringBuffer (String str) – This is used to create a string buffer with the given String content. Syntax:

StringBuffer a=new StringBuffer(“stringbuffer in java”);

Read: Difference Between String Buffers and String Builders

11 Popular Methods

1) StringBuffer in Java Append() Method

.append() is used to concatenate the given string and argument. Here’s an example:

import java.io.*;

public class buffer {

       public static void main(String[] args)

       {

                        StringBuffer a = new StringBuffer(“stringbuffer”);

                        a.append(“in Java”);

                        System.out.println(a);

                        a.append(0);

                        System.out.println(a);

       }

}

Output: 

2) StringBuffer in Java Insert() Method

.insert() method is used to insert a given string with the main string at the specified position. Here’s an example:

import java.io.*;

public class buffer {

       public static void main(String[] args)

       {

                        StringBuffer a = new StringBuffer(“stringbuffer”);

                        a.insert(5, “for”);

                        System.out.println(a);

                        a.insert(0, 5);

                        System.out.println(a);

                        a.insert(3, false);

                        System.out.println(a);

                        a.insert(5, 41.55d);

                        System.out.println(a);

                        a.insert(8, 41.55f);

                        System.out.println(a);

                        char arr[] = { ‘j’, ‘a’, ‘v’, ‘a’ };

                        a.insert(2, arr);

                        System.out.println(a);

       } }

Output:

 

Also Read: Java Project Ideas &  Topics

3) StringBuffer in java replace() method

.replace() is used to replace a part of string as specified in the range (beginIndex, endIndex). Here’s an example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“stringbuffer”);

                          a.replace(5, 8, “are”);

                          System.out.println(a); 

              }

}

Output:

4) StringBuffer in Java Delete() Method

.delete() is used to delete the string as specified in the range (beginIndex, endIndex).

.deleteCharAt() is used to delete the character at a specific index. This method returns the resulting stringbuffer object. Here’s an example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“string buffer in java”);

                          a.delete(0, 6);

                          System.out.println(a);

                          a.deleteCharAt(7);

                          System.out.println(a);

           }

}

Output: 

5) StringBuffer in Java Reverse() Method

.reverse() as the name suggests is used to reverse the given string. Here’s an example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“stringbuffer”);

                          a.reverse();

                          System.out.println(a);

           }

}

Output:

6) StringBuffer in Java Capacity() Method

.capacity() of StringBuffer in java class is used to return the current capacity of the buffer. 16 is the default capacity. The capacity increases by increasing the number of characters. The new capacity = (old capacity*2)+2. i.e., if the current capacity is 16, the new capacity will be 32+2=34.

.length is used to find the length of a StringBuffer in java. For example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“stringbuffer”);

                          int p = a.length();

                          int q = a.capacity();

                          System.out.println(“Length of string is=” + p);

                          System.out.println(“Capacity of string is=” + q);

           }

}

Output:

7) StringBuffer in Java ensureCapacity() Method

.ensureCapacity() of stringbuffer class is used to ensure that the specified capacity is the minimum to the current capacity. If the given capacity is greater than the current capacity, the new capacity becomes (oldcapacity*2)+2. i.e. the capacity becomes 34 if oldcapacity is 16. For example:

           public class buffer{ 

           public static void main(String args[]){ 

           StringBuffer a=new StringBuffer(); 

           System.out.println(a.capacity());

           a.append(“Hello”); 

           System.out.println(a.capacity());

           a.append(“java”); 

           System.out.println(a.capacity()); 

           a.ensureCapacity(10);

           System.out.println(a.capacity()); 

           a.ensureCapacity(50);

           System.out.println(a.capacity());

          

           }

Output:

Checkout: Java Developer Salary in India

8. charAt(int index) – This method is used to return the character at the given index.

9. substring( int begIndex) – This method is used to return a given string’s substring starting from the beginIndex.

10. substring(int beginIndex, int endIndex) – This method is used to return the given String’s substring starting at beginIndex and ending at endIndex.

11. void trimToSize() – This method is used to reduce storage space for the character sequence

Difference Between String and StringBuffer in Java

We use this example to create objects of the StringBuffer and String class and modify them. We see that the StringBuffer object gets modified, whereas String does not. See the example below:

public class buffer {

 public static void main(String args[])

 {

  String str = “string”;

  str.concat(“buffer”);

  System.out.println(str);

  StringBuffer strB = new StringBuffer(“string”);

  strB.append(“buffer”);

  System.out.println(strB);

 }

}

Output:

Explanation: The output is such because strings are immutable. If we try to concatenate the string object, it will not be altered. However, a StringBuffer in java creates mutable objects. Thus, it can be altered.

Interesting Points

  1. It extends the Object class.
  2. The implemented interfaces of StringBuffer in java are Appendable, Serializable, and CharSequence.
  3. The methods of StringBuffer can be synchronized wherever necessary. This means all operations behave as if they occur in some serial order.
  4. When an operation occurs involving the source sequence, this class synchronizes only on the string buffer operating and not the source.
  5. Some of the methods inherited from object class are equals, clone, getClass, notify, notifyAll, hashCode, and finalize.

Conclusion

StringBuffer in java creates modifiable string objects. Thus, we can use StringBuffer to append, replace, reverse, concatenate and modify the sequence of characters or strings. The methods under the StringBuffer class adhere to these functions. To sum up, StringBuffer in java is used only when multiple threads are modifying the contents of the StringBuffer. It is faster than String.

 In this article, we learned every detail about Java StringBuffer.If you are looking to learn more about java and move up in your technical career, explore courses by upGrad-India’s largest online higher education company.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Land on Your Dream Job

Executive PG Programme in Software Development - Specialisation in Full Stack Development
ENROLL TODAY

0 replies on “StringBuffer In Java: 11 Popular Methods Every Java Developer Should Know”

×