Programs

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

Check out our free courses to get an edge over the competition.

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.

Check out upGrad’s Advanced Certification in Cyber Security 

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”);

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

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

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

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:

Explore our Popular Software Engineering Courses

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:

Get Software Engineering degrees online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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

In-Demand Software Development Skills

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.

Explore Our Software Development Free Courses

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.

What exactly are Strings in Java?

Strings are Java objects that represent a sequence of characters. They can be created using either the String Literal or the NEW keyword. Strings in Java are immutable and are represented in UTF-16 format. When a new String is created, it searches the JVM string pool for a String with the same value. If it finds the same value, it returns the reference; otherwise, it creates a String object and adds it to the String pool. Aside from that, String uses the + operator to join two strings and internally uses the StringBuffer to do so.

What is the difference between StringBuffer and StringBuilder?

StringBuilder's function is very similar to that of the StringBuffer class in that both provide an alternative to String Class by creating a mutable sequence of characters. The StringBuilder class, on the other hand, differs from the StringBuffer class in terms of synchronization. The StringBuilder class does not provide synchronization guarantees, whereas the StringBuffer class does. As a result, this class is intended to be used as a drop-in replacement for StringBuffer in places where StringBuffer was previously used by a single thread (as is generally the case). It is recommended that this class be used instead of StringBuffer whenever possible because it is faster in most implementations. StringBuilder instances should not be used by multiple threads.

Why should you learn Java programming?

Java is an absolute must for students around the world who want to become great software engineers, especially if they work in the software development domain. Some of the primary benefits of learning Java programming include Object-Oriented applications. Because it is based on the Object model, Java can be extended. Java also is platform-independent, unlike many other programming languages, including C and C++. Moreover, it can be compiled into platform-independent bytecode rather than platform-specific machine code, which is distributed over the Internet for JVM interpretation.

Want to share this article?

Land on Your Dream Job

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks