Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero ornull, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
| Data Type | Default Value (for fields) |
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0d |
| char | '/u0000' |
| String (or any object) | null |
| boolean | false |
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
本文总结了不同数据类型在声明但未初始化时,编译器自动赋予的合理默认值,包括基本类型如byte、short、int等的默认值为0,float和double的默认值为0.0,char类型的默认值为'/u0000',String或其他对象类型的默认值为null,boolean类型的默认值为false,并指出局部变量未经初始化将导致编译错误。
4932

被折叠的 条评论
为什么被折叠?



