Use the toString() method of the StringBuffer class to convert the StringBuffer to a string
In Java, the StringBuffer class is a class used to handle variable strings. It provides many convenient methods to modify and Manipulate strings. When we need to convert a StringBuffer object into a string, we can use the toString() method to achieve this.
The toString() method of the StringBuffer class returns a String object, which contains the contents of the StringBuffer. Below is a sample code that shows how to convert a StringBuffer to a string using the toString() method:
public class StringBufferToStringExample { public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer("Hello"); String str = stringBuffer.toString(); System.out.println(str); } }
In the above code, we first create a StringBuffer object stringBuffer
, and Initialized to "Hello". Then, we call the toString()
method to convert the StringBuffer object into a string, and assign the result to a String type variable str
. Finally, we use the System.out.println()
method to print out the converted string.
Run the above code, the following results will be output:
Hello
In addition to the above example, we can also use the toString() method to convert StringBuffer objects in other scenarios. For example, we can splice the contents of multiple StringBuffer objects into one string:
public class StringBufferConcatenationExample { public static void main(String[] args) { StringBuffer stringBuffer1 = new StringBuffer("Hello"); StringBuffer stringBuffer2 = new StringBuffer(" World"); String str = stringBuffer1.append(stringBuffer2).toString(); System.out.println(str); } }
In the above code, we create two StringBuffer objects stringBuffer1
and stringBuffer2
, and initialized to "Hello" and "World" respectively. We then splice the contents of the two StringBuffer objects together using the append()
method and convert the result to a string via the toString()
method. Finally, we print the concatenated string.
Run the above code, the following results will be output:
Hello World
Summary:
By using the toString() method of the StringBuffer class, we can easily convert the StringBuffer object into a string. This is very practical in many scenarios, such as splicing strings, generating log information, etc. When you need to convert a StringBuffer object to a string, simply call the toString() method.
The above is the detailed content of Convert StringBuffer to string using toString() method of StringBuffer class. For more information, please follow other related articles on the PHP Chinese website!