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
廣告