Java StringBuilder toString() 方法



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

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

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

语法

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

public String toString()

参数

  • 它不接受任何参数。

返回值

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

示例:获取 StringBuilder 的字符串

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

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

public class Demo {
   public static void main(String[] args) {
      //instantiating the StringBuilder class
      StringBuilder sb = new StringBuilder("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

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

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

public class Demo {
   public static void main(String[] args) {
      //creating an object of the StringBuilder class
      StringBuilder sb = new StringBuilder("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_stringbuilder.htm
广告

© . All rights reserved.