简体   繁体   English

char数组(Java)中的空单元格的值是什么?

[英]What is the value of an empty cell in a char array (Java)?

Please consider this scenario: 请考虑以下情形:

char[] array = new char[4];
array[0] = 'a';
array[1] = '3';
array[3] = 'q';

As you can see, array[2] was never 'filled' with anything. 如您所见, array[2]从未被任何东西“填充”。 What would be the value of array[2] ? array[2]的值是多少?

What do I need to check for when iterating through a char array, looking for 'empty' cells? 遍历char数组以查找“空”单元时,我需要检查什么?

array[2] will be populated with the null char literal . array[2]将使用null char literal填充。 The value of which is \ . 其值为\

char is a primitive type. char是原始类型。 This means that it can never hold null , so like int , double and the rest, it needs some starting value. 这意味着它永远无法保持null ,因此像intdouble和其余的一样,它需要一些起始值。 For int it's 0 , for char it's \ , which actually evaluates to 0 . 对于int0 ,对于char\ ,其实际值为0

You can view the starting values for primitive types here . 您可以在此处查看基本类型的起始值。

The answer is: (char)0. 答案是:(字符)0。

Default values for primitives are 0, 0.0f, 0.0 (double), (char)0 and false (for boolean). 原语的默认值为0、0.0f,0.0(双精度),(char)0和false(对于布尔值)。

Applies to arrays and single variables. 适用于数组和单个变量。

In Java, char[] array = new char[4]; 在Java中, char[] array = new char[4]; will set all the memory associated to that array to zero. 将与该数组关联的所有内存设置为零。 In this case therefore each element will have the value of the null character literal '\\0' . 因此,在这种情况下,每个元素将具有空字符文字'\\0'

(This is not true for all languages, in C and C++, for example, the memory is unitialised and to access it before initialisation is, technically, undefined behaviour). (例如,对于所有语言,在C和C ++中并非如此,在技术上来说,内存是统一的,并且在初始化之前是无法定义的,因此可以对其进行访问)。

数组的空单元格始终为0,因为数组会自动由0初始化,因此它将为'0'

Like others already said, the default value will be null '\'. 就像其他人已经说过的一样,默认值将为null'\\ u0000'。 If you try to print it out, it will be an empty value. 如果尝试打印出来,它将是一个空值。 (Meaning you can't see it) (意味着您看不到它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM