Java - 簡短的 toString() 方法



Java Short toString() 方法檢索給定短整數值的字串表示形式。該值被轉換為帶符號十進位制數,並作為字串返回。

Java 中的 Short 物件是“Short”包裝類的例項,它儲存短整型原始資料型別。但是,在某些情況下,我們需要將 short 轉換為 String,因為這允許我們儲存 short 或其他儲存數字的資料型別(例如整數或浮點數)無法儲存的更大數字。

此方法有兩個多型變體;無引數和帶 short 引數(在下面的語法中討論)。

語法

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

public String toString() // without argument
or,
public static String toString(short s) // with a short argument

引數

  • s − 這是要轉換的 short 值。// 第二種語法

返回值

此方法返回此物件或引數的以 10 為基數的字串表示形式。(如果傳遞)。

獲取帶正值的 Short 的字串表示形式示例

下面給出的程式碼演示了 Java Short toString() 方法的使用方法,方法是建立一個 Short 物件。然後返回表示此 short 值的字串物件,無需傳遞任何引數:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      Short s = new Short("53");
      
      // returns a string representation
      String retval = s.toString();
      System.out.println("Value = " + retval);
   }
}

輸出

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

Value = 53

獲取帶正值的 Short 的字串表示形式示例

以下示例使用 try-catch 語句將 short 值賦值給字串物件 'str',從而將其轉換為等效的字串值:

package com.tutorialspoint;

import java.util.Scanner;

public class ShortDemo {
   public static void main(String[] args) {
      try {
         Short value1 = 98;
         
         // conversion to string
         String str = value1.toString();
         System.out.println("The equivalent string value is = " + str);
      } catch (Exception e) {
         System.out.println("Error: Invalid input!");
      }
      try {
         Short value2 = 0 * 64576;
         
         // conversion to string
         String str2 = value2.toString();
         System.out.println("The equivalent string value is = " + str2);
      } catch (Exception e) {
         System.out.println("Error: Invalid input!");
      }
   }
}

輸出

以下是上述程式碼的輸出:

The equivalent string value is = 98
The equivalent string value is = 0

獲取帶正值的 Short 的字串表示形式示例

以下是此方法的另一個示例:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      
      // create short object and assign value to it
      short sval = 50;   
      Short shortValue = new Short(sval);
      
      // returns a String object representing this Short value.
      System.out.println("Value is = " + shortValue.toString());
      
      // returns a String object representing the specified short
      System.out.println("Value of specified short is = " + Short.toString((short)sval));
   }
}   

輸出

上述程式碼的輸出如下:

Value is = 50
Value of specified short is = 50

獲取帶負值的 Short 的字串表示形式示例

在下面的示例中,我們也可以在一個具有負值的 Short 物件上呼叫 toString() 方法。

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      
      // create short object and assign value to it
      short sval = -50;
      Short shortValue = new Short(sval);
      
      // returns a String object representing this Short value.
      System.out.println("Value is = " + shortValue.toString());
   }
}  

輸出

執行上述程式碼後,我們將得到以下輸出:

Value is = -50
java_lang_short.htm
廣告