Primitives/Objects 声明,默认初始化值

2022-01-18 00:00:00 initialization default java

在声明原语/对象时,它们是否被初始化?

哪些是默认值?

类成员和本地字段的行为是什么?

类成员上的对象声明呢?

<小时>

如下所述,这些是默认值:

<块引用>

数据类型 - 默认值(用于字段)字节 0短 0整数 0长0L浮动 0.0f双0.0d字符 'u0000'字符串(或任何对象) null布尔假

请注意,对象被初始化为null

解决方案

int 的默认值是 0,它在 JavaSE 和JavaEE,除非它被分配了另一个值.

Java(或任何其他原语)中不能有未初始化的 int 类成员.

在您的示例中,您显示 int 是一个类成员,在另一个示例中它是一个局部变量,这就是区别.

对于 class members JVM 会放置默认值,对于 local variables 它让你在访问变量之前分配和初始值.

您可以查看 Default Values 部分>原始数据类型了解有关类成员默认值的更多信息.

When declaring primitives/objects, are them initialized?

Which are the default value?

What is the behavior on class members and local fields?

What about objects declaration on class members?


As answered below, these are the default values:

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

Please note that objects are initialized as null

解决方案

The default value of int is 0 and that is the value it will have in both JavaSE and JavaEE unless it was assigned with another value.

You can't have an uninitialized int class member in Java (or any other primitive).

In your example you show the int is a class member, in the other example its a local variable, that is the difference.

For class members JVM will put the default values, for a local variables it makes you assign and initial value before accessing the variable.

You can check the Default Values section in Primitive Data Types for more information about the class members default values.

相关文章