為什麼 Java 嚴格指定其基本型別的範圍和行為?


Java 提供多種資料型別用於儲存各種資料值。它提供 7 種基本資料型別(儲存單個值),即 boolean、byte、char、short、int、long、float 和 double。

Java 嚴格限定所有基本資料型別的範圍和行為。使用者根據應用程式選擇所需資料型別,從而減少記憶體的未用空間。

例如,如果你需要儲存一個單位數的整數常量,那麼使用 integer 將浪費記憶體,但你可以使用 byte 型別,因為儲存它只需要 8 位。

示例

下面的 Java 示例列出了基本資料型別的範圍。

public class PrimitiveDatatypes {
   public static void main(String[] args) {
      System.out.println("Minimum value of the integer type: "+Integer.MIN_VALUE);
      System.out.println("Maximum value of the integer type: "+Integer.MAX_VALUE);
      System.out.println(" ");
      System.out.println("Minimum value of the float type: "+Float.MIN_VALUE);
      System.out.println("Maximum value of the float type: "+Float.MAX_VALUE);
      System.out.println(" ");
      System.out.println("Minimum value of the double type: "+Double.MIN_VALUE);
      System.out.println("Maximum value of the double type: "+Double.MAX_VALUE);
      System.out.println(" ");
      System.out.println("Minimum value of the byte type: "+Byte.MIN_VALUE);
      System.out.println("Maximum value of the byte type: "+ Byte.MAX_VALUE);
      System.out.println(" ");
      System.out.println("Minimum value of the short type: "+Short.MIN_VALUE);
      System.out.println("Maximum value of the short type: "+Short.MAX_VALUE);
      System.out.println(" ");
      System.out.println("Minimum value of the long type: "+Long.MIN_VALUE);
      System.out.println("Maximum value of the long type: "+Long.MAX_VALUE);
   }
}

輸出

Minimum value of the integer type: -2147483648
Maximum value of the integer type: 2147483647

Minimum value of the float type: 1.4E-45
Maximum value of the float type: 3.4028235E38

Minimum value of the double type: 4.9E-324
Maximum value of the double type: 1.7976931348623157E308

Minimum value of the byte type: -128
Maximum value of the byte type: 127

Minimum value of the short type: -32768
Maximum value of the short type: 32767

Minimum value of the long type: -9223372036854775808
Maximum value of the long type: 9223372036854775807

更新於: 2019 年 8 月 1 日

253 次檢視

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告