Java - Integer toString() 方法



描述

Java Integer toString() 方法返回一個表示此 Integer 值的 String 物件。

宣告

以下是 java.lang.Integer.toString() 方法的宣告

public String toString()

引數

返回值

此方法返回此物件值的十進位制字串表示形式。

異常

使用正整數獲取 Integer 的字串表示形式示例

以下示例演示瞭如何使用 Integer toString() 方法獲取指定 int 值的字串表示形式。我們使用正 int 值建立了一個 Integer 物件。然後使用 toString() 方法,我們將字串表示形式儲存在一個變數中並打印出來。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      Integer i = new Integer(20);
   
      // returns a string representation of the integer value in base 10
      String retval = i.toString();
      System.out.println("Value = " + retval);
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Value = 20

使用負整數獲取 Integer 的字串表示形式示例

以下示例演示瞭如何使用 Integer toString() 方法獲取指定 int 值的字串表示形式。我們使用負 int 值建立了一個 Integer 物件。然後使用 toString() 方法,我們將字串表示形式儲存在一個變數中並打印出來。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {

      Integer i = new Integer(-20);
   
      // returns a string representation of the integer value in base 10
      String retval = i.toString();
      System.out.println("Value = " + retval);
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Value = -20

使用正零整數獲取 Integer 的字串表示形式示例

以下示例演示瞭如何使用 Integer toString() 方法獲取指定 int 值的字串表示形式。我們使用零值建立了一個 Integer 物件。然後使用 toString() 方法,我們將字串表示形式儲存在一個變數中並打印出來。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      Integer i = new Integer(0);
   
      // returns a string representation of the integer value in base 10
      String retval = i.toString();
      System.out.println("Value = " + retval);
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Value = 0
java_lang_integer.htm
廣告