Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconStringBuffer In Java: 11 Popular Methods Every Java Developer Should Know

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

Last updated:
25th May, 2021
Views
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
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.

Ads of upGrad blog

·  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:

Ads of upGrad blog

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What 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.

2What 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.

3Why 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.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas & Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions & Answers For Freshers & Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16879
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas & Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling & Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions & Answers 2024 [For Freshers & Experienced]
44555
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features & Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas & Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon