当我在 Java 中创建一个新的 String 时,它是用 null 还是用“”初始化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2812674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:08:59  来源:igfitidea点击:

When I create a new String in Java, is it initialized with null or with " "?

javastringinitialization

提问by

Here's my test code:

这是我的测试代码:

String foo = new String();
System.out.println(foo);

The output is blank and a new line is written. Since I'm new to Java, I don't know whether it made a " " string, or nulls are handled as blank lines.

输出为空白并写入一个新行。由于我是 Java 新手,我不知道它是否制作了 " " 字符串,或者空值被视为空行。

采纳答案by Chris Dennett

The string is initialised with no characters, or "" internally.

该字符串在内部初始化时没有字符或 ""。

public String() {
    this.offset = 0;
    this.count = 0;
    this.value = new char[0];
}

The above source is taken from the Java source code. As the other poster pointed out, references can either be null or point to an object, if you create a String object and get a reference to point to it, that reference will not be null.

以上源码取自Java源代码。正如另一位海报指出的那样,引用可以为空或指向一个对象,如果您创建一个 String 对象并获得指向它的引用,则该引用不会为空。

回答by DJClayworth

"null" is a value for a variable, not a value for a String. "foo" can have null value, but an actual String cannot. What you have done is create a new empty String (as the documentation for the constructor says) and assigned it to foo.

“null”是变量的值,而不是字符串的值。“foo”可以有空值,但实际的字符串不能。您所做的是创建一个新的空字符串(如构造函数的文档所述)并将其分配给 foo。

回答by Jay

new String() creates a String of length zero. If you simply said "String foo;" as a member variable, it would be initialized to null. If you say "String foo;" as a function variable, it is undefined, and will give a compile error if you try to use it without assigning a value.

new String() 创建一个长度为零的字符串。如果你只是说“String foo;” 作为成员变量,它会被初始化为 null。如果你说“String foo;” 作为函数变量,它是未定义的,如果您尝试使用它而不赋值,则会出现编译错误。

回答by someguy

A new line is printed because you called the println() method, which prints a line after printing whatever argument you passed. new String() will return "".

打印新行是因为您调用了 println() 方法,该方法在打印您传递的任何参数后打印一行。new String() 将返回 ""。

回答by OscarRyz

It is initialized with ""( empty string )

它用""(空字符串)初始化

public class StringTest {
    public static void main( String [] args ) {
        System.out.println( "".equals(new String()));
    }
}

prints:

印刷:

true