为什么 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
广告