Java StringBuffer toString() 方法



Java StringBuffer toString() 方法用于检索表示 StringBuffer 对象中数据的字符串。一个新的 String 对象被分配并初始化为包含此对象当前表示的字符序列。

Java 中的字符串是一个存储字符序列的对象。它由java.lang.string表示。字符串是常量,这意味着一旦字符串被初始化,我们就不能更改其值。

toString() 方法不接受任何参数,并且在将对象转换为字符串时不会抛出任何异常。

语法

以下是Java StringBuffer toString() 方法的语法:

public String toString()

参数

  • 它不接受任何参数。

返回值

此方法返回此字符序列的字符串表示形式。

示例:获取 StringBuffer 的字符串

如果StringBuffer 类对象不包含 null 值,则 toString() 方法会以字符串格式表示该对象。

在下面的程序中,我们使用值“TutorialsPoint”实例化StringBuffer类。使用toString()方法,我们尝试检索实例化对象的字符串表示形式。

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());
   }
}

输出

执行上述程序后,将产生以下结果:

The given string: TutorialsPoint
The string representation of an object: TutorialsPoint

示例:追加文本后获取 StringBuffer 的字符串

在下面的程序中,我们使用值“HelloWorld”创建一个StringBuffer 类的对象。然后,我们在其后追加一些值“India”。使用toString()方法,我们尝试检索该对象的字符串表示形式。

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());
   }
}

输出

以下是上述程序的输出:

The given string: HelloWorld
The string representation of an object: HelloWorld India.
java_lang_stringbuffer.htm
广告

© . All rights reserved.