英文:
Char array does not have null but String array does
问题
我正在尝试打印由矩形形状组成的二维数组,所以一个 4 行 4 列的矩阵看起来像这样:
* * * *
* *
* *
* * * *
我意识到可以通过以下代码来打印出这个矩阵:
int rows = 4;
int columns = 4;
char[][] rectangle = new char[rows][columns];
// 填充数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (i == 0 || j == 0 || i == rows - 1 || j == columns - 1) {
rectangle[i][j] = '*';
}
System.out.print(rectangle[i][j]);
}
System.out.println();
}
但是当我将数组类型从 char 更改为 String,并使用以下代码时:
int rows = 4;
int columns = 4;
String[][] rectangle = new String[rows][columns];
// 填充数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (i == 0 || j == 0 || i == rows - 1 || j == columns - 1) {
rectangle[i][j] = "* ";
}
System.out.print(rectangle[i][j]);
}
System.out.println();
}
它输出的结果如下:
* * * *
* nullnull*
* nullnull*
* * * *
我知道如何在使用 String 数组时修复这个问题,但我想知道为什么在使用 String 而不是 char 时会出现 null 值。
英文:
I am trying to print a 2D array formed by a rectangle so a 4 by 4 would be something like this:
* * * *
* *
* *
* * * *
I realize that I can print that out through this code:
int rows = 4;
int columns = 4;
char[][] rectangle = new char[rows][columns];
// fill array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (i == 0 || j == 0 || i == rows - 1 || j == columns - 1) {
rectangle[i][j] = '*';
}
System.out.print(rectangle[i][j]);
}
System.out.println();
}
But when I change the array type from char to String with the code below:
int rows = 4;
int columns = 4;
String[][] rectangle = new String[rows][columns];
// fill array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (i == 0 || j == 0 || i == rows - 1 || j == columns - 1) {
rectangle[i][j] = "* ";
}
System.out.print(rectangle[i][j]);
}
System.out.println();
}
It returns this:
* * * *
* nullnull*
* nullnull*
* * * *
I know how to fix it when using the String array but I want to know why it has null values when it is a String but not char.
答案1
得分: 3
因为String
是对象,所以它可以有null
值,并且null是String的默认值。另一方面,char
是原始数据类型,它无法包含null
值。char的默认值是'\u0000'
。
英文:
well it is simply because String
is Object, so it can have null
value, and null is default value for String. On other side char
is primitive type it just can not contain null
value. Default value for char is '\u0000'
答案2
得分: 2
请查看Java核心数据类型的默认值:
请注意:
英文:
Have a look at default values of the Java core data types:
Note, that:
-
String
(or any object) has a default value -null
-
char
has a default value -'\u0000'
, which, in turn, represents a null character/terminator, that is a non-printing control character.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论