在 Java 中將 Long 轉換為數字基本資料型別


假設我們有一個 Long 物件。

Long myObj = new Long("9879");

現在,如果我們要將此 Long 轉換為 short 基本資料型別。為此,請使用內建 shortValue() 方法 −

// converting to short primitive types
short shortObj = myObj.shortValue();
System.out.println(shortObj);

以相同的方式將 Long 轉換為另一個數字基本資料型別 int。為此,請使用內建 intValue() 方法 −

// converting to int primitive types
int intObj = myObj.intValue();
System.out.println(intObj);

以下是一個示例,其中我們將 Long 轉換為數字基本型別 short、int、float 等 −

示例

 即時演示

public class Demo {
   public static void main(String[] args) {
      Long myObj = new Long("9879");
      // converting to numeric primitive types
      short shortObj = myObj.shortValue();
      System.out.println(shortObj);
      int intObj = myObj.intValue();
      System.out.println(intObj);
      float floatObj = myObj.floatValue();
      System.out.println(floatObj);
      double doubleObj = myObj.doubleValue();
      System.out.println(doubleObj);
   }
}

輸出

9879
9879
9879.0
9879.0

更新於: 2019 年 7 月 30 日

562 次瀏覽

開啟您的 職業

完成本課程即可獲得認證

開始
廣告