Java StringBuffer toString() Method



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.

Syntax

Following is the syntax of the Java StringBuffer toString() method −

public String toString()

Parameters

  • It does not accept any parameter.

Return Value

This method returns a string representation of this sequence of characters.

Example

If 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.

import java.lang.*;
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: TutorialsPoint

Example

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.

import java.lang.*;
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
Advertisements