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.