Java 是强类型的语言(strongly typed language),共有 8基本数据类型primitive types

整型(integer types)

Type Storage Requirement Range (inclusive) suffix
byte 1 byte -128 ~ 127 -
short 2 bytes -32768 ~ 32767 -
int 4 bytes 正负各约21亿 -
long 8 bytes - l / L
  • Java 没有“无符号整型”;
  • Java 中整形的数据类型大小是固定的,与平台位数无关;
  • 八进制以 0 为前缀 ,十六进制以 0x 或 0X 为前缀;
  • 从 Java 7 开始,可以用二进制表达一个数,二进制数以 0b 或 0B 为前缀;
  • 从 Java 7 开始,在数值表达中(无论进制)可以使用下划线,如 1_000_000 表示一百万。

浮点型(float-point types)

Type Storage Requirement Range suffix
float 4 bytes 小数点点后 6 或 7位 f / F
double 8 bytes 小数点后 15 位 d / D (optional)
  • 浮点型遵循 IEEE 754 标准(注意:“浮点数无法表示 0”和“规格化与非规格化”);
  • 没有加 f 或 F 尾缀的浮点数默认为 double 类型;
  • 可以使用十六进制数来表示浮点数,如 0.125 = 2可以表示为 0x1.0p-3。其中尾数用十六进制表示,指数用十进制表示,基底为 2 而不是 10,且应该用 p 而不是 e 表示;
  • 浮点型不适用于金融计算,应该考虑使用 DigDecimal类;
  • 浮点型无法精确地表示小数,如 3 * 0.1 == 0.3 永远返回 false

在浮点型中有三个特殊值来表示溢出或错误:

  • Positive infinity
  • Nagative infinity
  • NaN (not a number)
  1. // in Float class
  2. public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
  3. public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
  4. public static final float NaN = 0.0f / 0.0f;
  5. // in Double class
  6. public static final double POSITIVE_INFINITY = 1.0 / 0.0;
  7. public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
  8. public static final double NaN = 0.0d / 0.0;

Note: you cannot test: if (x == Double.NaN) // is never true you shoud test: if (Double.isNaN(x)); // check whether x is “not a number”

字符型(char type)

Type Storage Requirement
char 2 bytes
  • 在 Java 中,char 类型用来表示一个用 UTF-16编码的代码单元code unit)。

A code point is a code value that is associated with a character in an encoding scheme.

The character in the basic multilingual plane are represented as 16-bit values, called code units.

  • 一个 char 类型数据可以被表示为 \u0000 ~\uFFFF 之间的十六进制数。

  • “Unicode 转义”比“代码解析”先进行,这会产生不易发现的错误。例如:

// \u000A is newline

这行注释会报错,因为 \u000A 会被转义为换行,编译器会理解为:

// 
 is newline

可使用 \\ 防止 \ 转义。

尽量不要使用 char 类型,应使用 String 类字符串。

布尔型(boolean type)

在 Java 中,整型与布尔型不可转换,即没有 C/C++ 中非 0 为 true 的规定。

Java 语言规范中并没有规定 boolean 类型数据的大小,其大小与 jvm 有关,如代码所示:

// single boolean variable use 4 bytes because it is treated as int type by JVM
boolean a = true;    // use 4 bytes

// boolean array will be treated as byte array in JVM, so it use 1 byte
boolean[] b = new boolean[10];    // use 1 byte