java - 空数组自动初始化内容?

标签 java arrays initialization declaration

怎么会

int alone;
System.out.println(alone);

给出错误但是

 int[] arr = new int[1];
 System.out.println(arr[0]);

等于 0? 当你初始化一个空数组时,它会自动将其内容初始化为 0(或 null 等)吗?

最佳答案

来自 the language standard

Otherwise, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

默认值是:

  • 对于byte类型,默认值为0,即(byte)0的值。

  • 对于short类型,默认值为零,即(short)0的值。

  • 对于int类型,默认值为零,即0。

  • 对于long类型,默认值为零,即0L。

  • 对于float类型,默认值为正零,即0.0f。

  • 对于double类型,默认值为正零,即0.0d。

  • 对于char类型,默认值为空字符,即'\u0000'。

  • 对于boolean类型,默认值为false。

  • 对于所有引用类型 (§ 4.3),默认值为 null。

关于java - 空数组自动初始化内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13167153/

相关文章:

Android SparseArray<SparseArray<Object>> 初始化

java.lang.NullPointerException : inStream parameter is null while loading a properties file

c++ - 通过赋值初始化 C++ 对象时会发生什么?

c++ - 为什么我得到变量 -- is being used without being initialized 错误?

java将文件的输出存储到数组中

javascript - 比较正确的值并将其推送到 JavaScript/TypeScript 中的对象数组

java - 列表过滤: recreate from empty list,或复制并删除元素?

Java swing JButton 顺序和大小

java - 正则表达式 - 使用正则表达式搜索字符串并从原始字符串中提取匹配项

java - 两天的 hibernate 训练应该包括什么