search
HomeJavajavaTutorialDetailed explanation of the use of StringBuffer class in Java

StringBuffer is a thread-safe mutable character sequence. It inherits from AbstractStringBuilder and implements the CharSequence interface.
StringBuilder is also a subclass inherited from AbstractStringBuilder; however, StringBuilder is different from StringBuffer. The former is non-thread safe and the latter is thread safe.
The relationship diagram between StringBuffer and CharSequence is as follows:

Detailed explanation of the use of StringBuffer class in Java

The StringBuffer class is the same as String and is also used to represent strings, but because the internal implementation of StringBuffer is different from String Different, so StringBuffer does not generate new objects when processing strings, and its memory usage is better than the String class.
So in actual use, if you often need to modify a string, such as insertion, deletion and other operations, it is more suitable to use StringBuffer.
There are many methods in the StringBuffer class that are the same as those in the String class. These methods are exactly the same in function as those in the String class.
But one of the most significant differences is that every modification to the StringBuffer object will change the object itself. This is the biggest difference from the String class.

In addition, since StringBuffer is thread-safe, the concept of threads will be introduced in a special chapter later, so it can also be used easily in multi-threaded programs, but the execution efficiency of the program is relatively low. Slightly slower.

0. Initialization of StringBuffer object

The initialization of StringBuffer object is not the same as the initialization of String class. Java provides special syntax, and usually the constructor method is used for initialization.
For example:

StringBuffer s = new StringBuffer();

The StringBuffer object initialized in this way is an empty object.
If you need to create a StringBuffer object with content, you can use:

StringBuffer s = new StringBuffer(“abc”);

The content of the initialized StringBuffer object is the string "abc".
It should be noted that StringBuffer and String belong to different types, and they cannot be directly cast. The following codes are wrong:

StringBuffer s = “abc”;        //赋值类型不匹配
StringBuffer s = (StringBuffer)”abc”;  //不存在继承关系,无法进行强转

StringBuffer object and String object The code for mutual conversion is as follows:

String s = “abc”;
StringBuffer sb1 = new StringBuffer(“123”);
StringBuffer sb2 = new StringBuffer(s);  //String转换为StringBuffer
String s1 = sb1.toString();       //StringBuffer转换为String

1. StringBuffer function list

StringBuffer()
StringBuffer(int capacity)
StringBuffer(String string)
StringBuffer(CharSequence cs)
 
StringBuffer  append(boolean b)
StringBuffer  append(int i)
StringBuffer  append(long l)
StringBuffer  append(float f)
StringBuffer  append(double d)
synchronized StringBuffer  append(char ch)
synchronized StringBuffer  append(char[] chars)
synchronized StringBuffer  append(char[] chars, int start, int length)
synchronized StringBuffer  append(Object obj)
synchronized StringBuffer  append(String string)
synchronized StringBuffer  append(StringBuffer sb)
synchronized StringBuffer  append(CharSequence s)
synchronized StringBuffer  append(CharSequence s, int start, int end)
StringBuffer  appendCodePoint(int codePoint)
int  capacity()
synchronized char  charAt(int index)
synchronized int  codePointAt(int index)
synchronized int  codePointBefore(int index)
synchronized int  codePointCount(int beginIndex, int endIndex)
synchronized StringBuffer  delete(int start, int end)
synchronized StringBuffer  deleteCharAt(int location)
synchronized void  ensureCapacity(int min)
synchronized void  getChars(int start, int end, char[] buffer, int idx)
synchronized int  indexOf(String subString, int start)
int  indexOf(String string)
StringBuffer  insert(int index, boolean b)
StringBuffer  insert(int index, int i)
StringBuffer  insert(int index, long l)
StringBuffer  insert(int index, float f)
StringBuffer  insert(int index, double d)
synchronized StringBuffer  insert(int index, char ch)
synchronized StringBuffer  insert(int index, char[] chars)
synchronized StringBuffer  insert(int index, char[] chars, int start, int length)
synchronized StringBuffer  insert(int index, String string)
StringBuffer  insert(int index, Object obj)
synchronized StringBuffer  insert(int index, CharSequence s)
synchronized StringBuffer  insert(int index, CharSequence s, int start, int end)
int  lastIndexOf(String string)
synchronized int  lastIndexOf(String subString, int start)
int  length()
synchronized int  offsetByCodePoints(int index, int codePointOffset)
synchronized StringBuffer  replace(int start, int end, String string)
synchronized StringBuffer  reverse()
synchronized void  setCharAt(int index, char ch)
synchronized void  setLength(int length)
synchronized CharSequence  subSequence(int start, int end)
synchronized String  substring(int start)
synchronized String  substring(int start, int end)
synchronized String  toString()
synchronized void  trimToSize()

2. StringBuffer example
The source code is as follows ( StringBufferTest.java):

/**
 * StringBuffer 演示程序
 */
import java.util.HashMap;
 
public class StringBufferTest {
 
 public static void main(String[] args) {
  testInsertAPIs() ;
  testAppendAPIs() ;
  testReplaceAPIs() ;
  testDeleteAPIs() ;
  testIndexAPIs() ;
  testOtherAPIs() ;
 }
 
 /**
  * StringBuffer 的其它API示例
  */
 private static void testOtherAPIs() {
 
  System.out.println("-------------------------------- testOtherAPIs --------------------------------");
 
  StringBuffer sbuilder = new StringBuffer("0123456789");
 
  int cap = sbuilder.capacity();
  System.out.printf("cap=%d\n", cap);
 
  char c = sbuilder.charAt(6);
  System.out.printf("c=%c\n", c);
 
  char[] carr = new char[4];
  sbuilder.getChars(3, 7, carr, 0);
  for (int i=0; i<carr.length; i++)
   System.out.printf("carr[%d]=%c ", i, carr[i]);
  System.out.println();
 
  System.out.println();
 }
 
 /**
  * StringBuffer 中index相关API演示
  */
 private static void testIndexAPIs() {
  System.out.println("-------------------------------- testIndexAPIs --------------------------------");
 
  StringBuffer sbuilder = new StringBuffer("abcAbcABCabCaBcAbCaBCabc");
  System.out.printf("sbuilder=%s\n", sbuilder);
 
  // 1. 从前往后,找出"bc"第一次出现的位置
  System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc"));
 
  // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置
  System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5));
 
  // 3. 从后往前,找出"bc"第一次出现的位置
  System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc"));
 
  // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置
  System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\", 4)", sbuilder.lastIndexOf("bc", 4));
 
  System.out.println();
 }
 
 /**
  * StringBuffer 的replace()示例
  */
 private static void testReplaceAPIs() {
 
  System.out.println("-------------------------------- testReplaceAPIs ------------------------------");
 
  StringBuffer sbuilder;
 
  sbuilder = new StringBuffer("0123456789");
  sbuilder.replace(0, 3, "ABCDE");
  System.out.printf("sbuilder=%s\n", sbuilder);
 
  sbuilder = new StringBuffer("0123456789");
  sbuilder.reverse();
  System.out.printf("sbuilder=%s\n", sbuilder);
 
  sbuilder = new StringBuffer("0123456789");
  sbuilder.setCharAt(0, &#39;M&#39;);
  System.out.printf("sbuilder=%s\n", sbuilder);
 
  System.out.println();
 }
 
 /**
  * StringBuffer 的delete()示例
  */
 private static void testDeleteAPIs() {
 
  System.out.println("-------------------------------- testDeleteAPIs -------------------------------");
 
  StringBuffer sbuilder = new StringBuffer("0123456789");
 
  // 删除位置0的字符,剩余字符是“123456789”。
  sbuilder.deleteCharAt(0);
  // 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。
  sbuilder.delete(3,6);
 
  // 获取sb中从位置1开始的字符串
  String str1 = sbuilder.substring(1);
  // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串
  String str2 = sbuilder.substring(3, 5);
  // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String
  String str3 = (String)sbuilder.subSequence(3, 5);
 
  System.out.printf("sbuilder=%s\nstr1=%s\nstr2=%s\nstr3=%s\n",
    sbuilder, str1, str2, str3);
 
  System.out.println();
 }
 
 /**
  * StringBuffer 的insert()示例
  */
 private static void testInsertAPIs() {
 
  System.out.println("-------------------------------- testInsertAPIs -------------------------------");
 
  StringBuffer sbuilder = new StringBuffer();
 
  // 在位置0处插入字符数组
  sbuilder.insert(0, new char[]{&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;});
  // 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度
  sbuilder.insert(0, new char[]{&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;}, 0, 3);
  // 在位置0处插入float
  sbuilder.insert(0, 1.414f);
  // 在位置0处插入double
  sbuilder.insert(0, 3.14159d);
  // 在位置0处插入boolean
  sbuilder.insert(0, true);
  // 在位置0处插入char
  sbuilder.insert(0, &#39;\n&#39;);
  // 在位置0处插入int
  sbuilder.insert(0, 100);
  // 在位置0处插入long
  sbuilder.insert(0, 12345L);
  // 在位置0处插入StringBuilder对象
  sbuilder.insert(0, new StringBuffer("StringBuilder"));
  // 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括)
  sbuilder.insert(0, new StringBuffer("STRINGBUILDER"), 6, 13);
  // 在位置0处插入StringBuffer对象。
  sbuilder.insert(0, new StringBuffer("StringBuffer"));
  // 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括)
  sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12);
  // 在位置0处插入String对象。
  sbuilder.insert(0, "String");
  // 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括)
  sbuilder.insert(0, "0123456789", 1, 6);
  sbuilder.insert(0, &#39;\n&#39;);
 
  // 在位置0处插入Object对象。此处以HashMap为例
  HashMap map = new HashMap();
  map.put("1", "one");
  map.put("2", "two");
  map.put("3", "three");
  sbuilder.insert(0, map);
 
  System.out.printf("%s\n\n", sbuilder);
 }
 
 /**
  * StringBuffer 的append()示例
  */
 private static void testAppendAPIs() {
 
  System.out.println("-------------------------------- testAppendAPIs -------------------------------");
 
  StringBuffer sbuilder = new StringBuffer();
 
  // 追加字符数组
  sbuilder.append(new char[]{&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;});
  // 追加字符数组。0表示字符数组起始位置,3表示长度
  sbuilder.append(new char[]{&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;}, 0, 3);
  // 追加float
  sbuilder.append(1.414f);
  // 追加double
  sbuilder.append(3.14159d);
  // 追加boolean
  sbuilder.append(true);
  // 追加char
  sbuilder.append(&#39;\n&#39;);
  // 追加int
  sbuilder.append(100);
  // 追加long
  sbuilder.append(12345L);
  // 追加StringBuilder对象
  sbuilder.append(new StringBuffer("StringBuilder"));
  // 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括)
  sbuilder.append(new StringBuffer("STRINGBUILDER"), 6, 13);
  // 追加StringBuffer对象。
  sbuilder.append(new StringBuffer("StringBuffer"));
  // 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括)
  sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12);
  // 追加String对象。
  sbuilder.append("String");
  // 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括)
  sbuilder.append("0123456789", 1, 6);
  sbuilder.append(&#39;\n&#39;);
 
  // 追加Object对象。此处以HashMap为例
  HashMap map = new HashMap();
  map.put("1", "one");
  map.put("2", "two");
  map.put("3", "three");
  sbuilder.append(map);
  sbuilder.append(&#39;\n&#39;);
 
  // 追加unicode编码
  sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码
  sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码
  sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码
  sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码
 
  System.out.printf("%s\n\n", sbuilder);
 }
}

Run result:

-------------------------------- testInsertAPIs -------------------------------
{3=three, 2=two, 1=one}
12345StringBUFFERStringBufferBUILDERStringBuilder12345100
true3.141591.414ABCabcde
 
-------------------------------- testAppendAPIs -------------------------------
abcdeABC1.4143.14159true
10012345StringBuilderBUILDERStringBufferBUFFERString12345
{3=three, 2=two, 1=one}
字符编码
 
-------------------------------- testReplaceAPIs ------------------------------
sbuilder=ABCDE3456789
sbuilder=9876543210
sbuilder=M123456789
 
-------------------------------- testDeleteAPIs -------------------------------
sbuilder=123789
str1=23789
str2=78
str3=78
 
-------------------------------- testIndexAPIs --------------------------------
sbuilder=abcAbcABCabCaBcAbCaBCabc
sbuilder.indexOf("bc")   = 1
sbuilder.indexOf("bc", 5)  = 22
sbuilder.lastIndexOf("bc")  = 22
sbuilder.lastIndexOf("bc", 4) = 4
 
-------------------------------- testOtherAPIs --------------------------------
cap=26
c=6
carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6

More details on Java For articles related to the use of the StringBuffer class in the string buffer, please pay attention to 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
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment