Java.lang.StringBuilder.toString() Method


Advertisements


Description

The java.lang.StringBuilder.toString() method returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object.

Declaration

Following is the declaration for java.lang.StringBuilder.toString() method

public String toString()

Parameters

NA

Return Value

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

Exception

NA

Example

The following example shows the usage of java.lang.StringBuilder.toString() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBuilderDemo {

   public static void main(String[] args) {
  
      StringBuilder str = new StringBuilder("India ");
      System.out.println("string = " + str);

      // append character to the StringBuilder
      str.append('!');
      
      // convert to string object and print it
      System.out.println("After append = " + str.toString());
      
      str = new StringBuilder("Hi "); 
      System.out.println("string = " + str);
      
      // append integer to the StringBuilder
      str.append(123);
   
      // convert to string object and print it
      System.out.println("After append = " + str.toString());
   }
}

Let us compile and run the above program, this will produce the following result −

string = India
After append = India !
string = Hi
After append = Hi 123

java_lang_stringbuilder.htm

Advertisements