Java StringBuffer and StringBuilder Classes
\nWhen modifying strings, you need to use the StringBuffer and StringBuilder classes.
Unlike the String class, objects of StringBuffer and StringBuilder can be modified multiple times without creating new, unused objects.
!(#)
\nWhen using the StringBuffer class, operations are performed on the StringBuffer object itself, rather than generating a new object. Therefore, if you need to modify a string, it is recommended to use StringBuffer.
The StringBuilder class was introduced in Java 5. The biggest difference between it and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).
Since StringBuilder has a speed advantage over StringBuffer, it is recommended to use the StringBuilder class in most cases.
Example
\npublic class TutorialTest{\n public static void main(String[]args){\n StringBuilder sb = new StringBuilder(10);\n sb.append("Tutorial..");\n System.out.println(sb);\n sb.append("!");\n System.out.println(sb);\n sb.insert(8, "Java");\n System.out.println(sb);\n sb.delete(5,8);\n System.out.println(sb);\n }\n}\n\n!(#)
\nThe compilation and execution results of the above example are as follows:
\nTutorial..\nTutorial..!\nTutorial..Java!\nRunooJava!\n\nHowever, in cases where thread safety is required by the application, the StringBuffer class must be used.
Test.java File Code:
\npublic class Test{\n public static void main(String[]args){\n StringBuffer sBuffer = new StringBuffer("Official Website:");\n sBuffer.append("www");\n sBuffer.append(".tutorial");\n sBuffer.append(".com");\n System.out.println(sBuffer);\n }\n}\n\nThe compilation and execution results of the above example are as follows:
\nOfficial Website: example.com\n\n\nStringBuffer Methods
\nThe following are the main methods supported by the StringBuffer class:
| No. | Method Description |
|---|---|
| 1 | public StringBuffer append(String s) Appends the specified string to this character sequence. |
| 2 | public StringBuffer reverse() Replaces this character sequence with its reverse. |
| 3 | public delete(int start, int end) Removes the characters in a substring of this sequence. |
| 4 | public insert(int offset, int i) Inserts the string representation of the int parameter into this sequence. |
| 5 | insert(int offset, String str) Inserts the string representation of the str parameter into this sequence. |
| 6 | replace(int start, int end, String str) Replaces the characters in a substring of this sequence with characters in the specified String. |
The following list shows other common methods of the StringBuffer class:
| No. | Method Description |
|---|---|
| 1 | int capacity() Returns the current capacity. |
| 2 | char charAt(int index) Returns the char value at the specified index in this sequence. |
| 3 | void ensureCapacity(int mi Ensures that the capacity is at least equal to the specified minimum. |
YouTip