search
HomeJavajavaTutorialStringBuffer Class in Java

As we know that there are basically two types of java objects, they are mutable and immutable. Immutable objects are those objects whose contents cannot be modified once created. Whenever the content of an immutable object is changed, there will be the creation of new objects. In the case of a mutable object, we can change the contents of an existing object which does not result in the creation of a new object. Therefore mutable strings are those strings whose content can be changed without creating new objects.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

StringBuffer and StringBuilder are mutable versions of String in java, whereas the java String class is immutable. Therefore StringBuffer is a mutable String used to provide mutability to String Objects. String class contains a fixed-length, immutable sequence of characters, whereas string buffer has an expandable length and writable sequence of characters.

How to Use String Buffer Class in Java?

Here are some points which show how we can use StringBuffer in java.

  • As already covered, the mutable string in java can be created using StringBuffer and StringBuilder classes.
  • The main difference between the two is that StringBuffer is a thread-safe implementation, whereas StringBuilder is not.
  • Whenever high performance and high security is required, one should prefer mutable versions of the String class.
  • Because of the String pool, there are security issues with the String class; therefore, StringBuffer is used whenever data security is necessary.
  • StringBuffer is better in terms of performance than StringBuffer as StringBuffer is thread-safe, but whenever thread safety is necessary, one should go for StringBuffer.

StringBuffer Constructors

The following are String buffer constructors:

  • StringBuffer(): This creates an empty StringBuffer with a default capacity of 16 characters.
  • StringBuffer(int capacity): This creates an empty StringBuffer with a specified capacity.
  • StringBuffer(CharSequence charseq): This creates StringBuffer containing the same characters as in the specified character sequence.
  • StringBuffer(String str): Creates a StringBuffer corresponding to specified String.

Here is the declaration of StringBuffer Class:

public final class StringBuffer extends Object implements Serializable,CharacterSequence,Appendable

Methods of StringBuffer Class in Java

Now we will see what different methods and fields available in StringBuffer are. Here is the list of commonly used methods available in the StringBuffer class:

Method Name Description
length() and capacity() The length of a mutable string can be calculated using the length() method, and corresponding capacity can be calculated using capacity().
append(String str)

append(int number)

This method is used for adding new text at the end of an existing string buffer.
insert(int index, String str)

insert(int index, char ch)

Used for inserting text at a specified position in a given string. In the given syntax index specifies the starting index of at which the string will be inserted.
reverse() Used for reversing the order of character in a given string buffer object.
delete(int start, int end) and deleteCharAt(int index) Used for deleting characters from a string buffer. Start indicates the starting index of the first character to be removed, and the end indicates an index of one past the last character to be removed.
replace(int startindex, int endindex, String str) Used for replacing character sequence between startindex and endindex-1 with the specified string buffer.
charAt(int index) Used to return character at the specified index in String buffer.
codePointAt(int index) Used to return the Unicode of character at the specified index.
codePointBefore(int index) Used to return the Unicode of character before the specified index.
substring(int start)

substring(int start, int end)

Used to return a new String that contains a subsequence of characters contained in a given string.
ensureCapacity(int capacity) Used for increasing the capacity of an existing string buffer object.
toString() Used to convert mutable string buffer to an immutable string object.

Examples of StringBuffer Class in Java

Here are some of the examples of StringBuffer class which are given below:

Example #1

Let us see a basic example of the StringBuffer class.

Code:

public class StringBufferDemo{
public static void main(String args[]){
StringBuffer sBuffer1=new StringBuffer("Welcome");
System.out.println("Original String is ::: " + sBuffer1 + ":: having length " + sBuffer1.length());
//using append method
sBuffer1.append(" To Edubca");
System.out.println("Modified String after append is :: " + sBuffer1 + " :: having length " + sBuffer1.length());
//using reverse method
sBuffer1.reverse();
System.out.println("Modified String after Reverse is :: " + sBuffer1);
}
}

The above code shows the creation of java StringBuffer and its different methods. The following output will be produced.

Output:

StringBuffer Class in Java

Example #2

In this example, we will see some more methods of the StringBuffer class.

Code:

public class StringBufferDemo{
public static void main(String args[]){
StringBuffer sBuffer=new StringBuffer ("WelcomeToEdubca");
System.out.println("Original String is ::: " + sBuffer + ":: having length " + sBuffer.length());
//using replace method
sBuffer.replace(0,9,"This is ");
System.out.println("Modified String after replace is :: " + sBuffer + " :: having length " + sBuffer.length());
//using delete method
sBuffer.delete(0,7);
System.out.println("Modified String after delete is :: " + sBuffer);
}
}

The above code will display the following as output.

 Output:

StringBuffer Class in Java

In the above example, we have seen how to create a StringBuffer class and usage of its methods.

Conclusion

From the above discussion, we have a clear understanding of StringBuffer in java, how it is created, and the different methods available in the StringBuffer class. Also, StringBuffer is thread-safe; therefore, it can be used in a multithreading environment.

The above is the detailed content of StringBuffer Class in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools