Java中数组的默认初始化是什么? [英] What is the default initialization of an array in Java?

查看:21
本文介绍了Java中数组的默认初始化是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我声明并初始化一个 int 数组:

So I'm declaring and initializing an int array:

static final int UN = 0;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
    arr[i] = UN;
}

说我这样做...

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

... 0 将打印到标准输出.另外,如果我这样做:

... 0 will print to standard out. Also, if I do this:

static final int UN = 0;
int[] arr = new int[5];
System.out.println(arr[0]==UN);

... true 将打印到标准输出.那么默认情况下 Java 是如何初始化我的数组的呢?假设默认初始化将数组索引设置为 0 是否安全,这意味着我不必遍历数组并初始化它?

... true will print to standard out. So how is Java initializing my array by default? Is it safe to assume that the default initialization is setting the array indices to 0 which would mean I don't have to loop through the array and initialize it?

谢谢.

推荐答案

Java 程序中未由程序员显式设置的所有内容都被初始化为零值.

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • 对于 null 的引用(任何包含对象的东西).
  • 对于 int/short/byte/long 即 0.
  • 对于 0.0
  • 的 float/double
  • 对于 false 的布尔值.
  • 对于 char 是空字符 'u0000'(其十进制等效值为 0).
  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character 'u0000' (whose decimal equivalent is 0).

当你创建一个数组时,所有的条目也会被清零.所以您的数组在由 new 创建后立即包含五个零.

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

注意(基于注释):Java 虚拟机在分配局部变量时不需要将底层内存清零(如果需要,这允许有效的堆栈操作),因此为了避免随机值,Java 语言规范要求局部变量已初始化.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

这篇关于Java中数组的默认初始化是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆