Java - String toString() 方法



描述

此方法是從 Object 類重寫而來。通常,toString() 方法返回當前物件的字串表示形式。Java String toString() 方法用於檢索字串本身,並將結果表示為文字格式。因此,此處沒有進行實際的轉換。

Java 中的字串是一組字元,它是 Java lang 類的物件。Java 中的字串類用於建立和修改字串。字串在建立後其值不能被修改。無需在字串物件上顯式呼叫此方法,它只是返回當前字串而無需進行任何更改。通常此方法隱式呼叫。

語法

以下是Java String toString() 方法的語法:

public String toString()

引數

此方法不接受任何引數。

返回值

此方法返回字串本身。

獲取字串物件的字串表示形式示例

在下面給出的示例中,建立了一個值為“Welcome to Tutorials Point”的 String 物件。然後,我們在建立的字串上呼叫 toString() 方法:

package com.tutorialspoint;

public class StringDemo {
   public static void main(String args[]) {
      String obj = new String("Welcome to Tutorials Point");
      System.out.println("The string is: " + obj.toString());
   }
}

輸出

如果編譯並執行上面的程式,則輸出將顯示如下:

The string is: Welcome to Tutorials Point

獲取整數的字串表示形式示例

以下示例顯示了 Java String toString() 方法的使用,用於將整數轉換為其等效的字串值:

package com.tutorialspoint;

public class StringDemo {
   public static void main(String[] args) {
      
      // converts integer value in String representation
      int val1 = 325;
      String str1 = Integer.toString(val1);
      System.out.println("String representation of integer value = " + str1);    
   }
}

輸出

如果編譯並執行上述程式,它將產生以下結果:

String representation of integer value = 325

獲取雙精度數的字串表示形式示例

下面是一個示例,使用 Java 中的 toString() 方法將雙精度值轉換為其等效字串:

package com.tutorialspoint;

public class StringDemo {
   public static void main(String[] args) {
      
      // converts double value in String representation
      double val2 = 876.23;
      String str2 = Double.toString(val2);
      System.out.println("String representation of double value = " + str2);
   }
}

輸出

執行上述程式後,輸出如下所示:

String representation of double value = 876.23

獲取物件的字串表示形式示例

在下面的程式碼中,我們定義了一個名為 Vehicle 的類,並建立了它的兩個物件 'v1' 和 'v2'。由於 Java 中的 toString() 方法在物件上工作,當列印 'v1' 和 'v2' 的值時,此方法被隱式呼叫。

class Vehicle {
   String brand;
   Integer modelNumber;
   Vehicle(String brand, Integer modelNumber) {
      
      // constructor to initialize variables of the class
      this.brand = brand;
      this.modelNumber = modelNumber;
   }
}
public class StringDemo {
   public static void main(String args[]) {
      Vehicle v1 = new Vehicle("Mahindra", 700);
      Vehicle v2 = new Vehicle("Maruti", 800);
      
      // The toString() method is called implicitly
      System.out.println("The value of object v1 is: " + v1);
      System.out.println("The value of object v2 is: " + v2);
   }
}

輸出

上面程式碼的輸出分為兩部分。第一部分是物件的類,第二部分是 toString() 方法返回的物件的十六進位制程式碼,如下所示:

The value of object v1 is: Vehicle@2c7b84de
The value of object v2 is: Vehicle@3fee733d
java_lang_string.htm
廣告