StringBuffer 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:
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
