- 基本表述
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
java类变量在加载阶段时,JVM会为基本数据类型(byte、short、int、long、float、double以及char、boolean)赋值为默认值,直到初始化阶段才将给定的初始值赋值给基本类型的类变量,覆盖其默认值。其初始值如表(英文表述引用):
类型 | 初始值 |
---|---|
byte | (byte)0 |
short | (short)0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | ‘\u0000’(null) |
boolean | false |
- 注意
1. 当基本数据类型被声明为非类变量时,JVM不会为相应的数据类型提供默认值,此时需要显示设置初始值才能正常使用基本类型,否则会提示The local variable * may not have been initialized;
2. Java将数据类型分为基本数据类型和引用类型,在作为类变量使用时,为显示初始化的引用类型类变量也会被初始化为默认值(null);
3. Java为8中基本数据类型都提供了相应的包装类(Byte、Short、Integer、Long、Float、Double以及Character、Boolean),并且基本数据类型对应的包装类为引用类型,JVM会为其赋值默认值(null)。