The Java StringBuffer toString() method is used to retrieve a string representing the data in a StringBuffer object. A new String object is allocated and initialized to contain the character sequence currently represented by this object.
A String in Java is an object that stores a sequence of characters. It is represented by the java.lang.string. A string is a constant, which means that we cannot change the string value once it has been initialized.
The toString() method does not accept any parameter, and it does not throw any exception while converting an object to a string.
SyntaxFollowing is the syntax of the Java StringBuffer toString() method −
public String toString()Parameters
This method returns a string representation of this sequence of characters.
Example: Getting String of StringBufferIf the StringBuffer class object does not contain the null value, the toString() method represents the object in a string format.
In the following program, we are instantiating the StringBuffer class with the value TutorialsPoint. Using the toString() method, we are trying to retrieve the string representation of the instantiated object.
public class Demo { public static void main(String[] args) { //instantiating the StringBuffer class StringBuffer sb = new StringBuffer("TutorialsPoint"); System.out.println("The given string: " + sb); //using the toString() method System.out.println("The string representation of an object: " + sb.toString()); } }Output
On executing the above program, it will produce the following result −
The given string: TutorialsPoint The string representation of an object: TutorialsPointExample: Getting String of StringBuffer After Appending a Text
In the following program, we are creating an object of the StringBuffer class with the value HelloWorld. Then, we append some value India to it. Using the toString() method, we are trying to retrieve the string representation of the object.
public class Demo { public static void main(String[] args) { //creating an object of the StringBuffer class StringBuffer sb = new StringBuffer("HelloWorld"); System.out.println("The given string: " + sb); //append some value to it using append() method. sb.append(" India."); //using the toString() method System.out.println("The string representation of an object: " + sb.toString()); } }Output
Following is the output of the above program −
The given string: HelloWorld The string representation of an object: HelloWorld India.
java_lang_stringbuffer.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4