简体   繁体   English

Java字符串的默认值:null与“”

[英]Default value of Java String: null vs “”

The default value of a Java String is 'null'. Java字符串的默认值为'null'。 However, when I instantiate the string, it seems to be an empty string instead. 但是,当我实例化字符串时,它似乎是一个空字符串。 Can somebody explain this please ? 有人可以解释一下吗?

class Stuff
{
    String a;
    String b = new String();
}

class Demo
{
    public static void main( String[] args )
    {
       Stuff s = new Stuff();
       System.out.println( s.a );
       System.out.println( s.b );

       if( s.b.equals( "" ) )
       {
            System.out.println( "true" );
       }
    }
}

The String() constructor Javaodc says, String()构造函数Javaodc说,

Initializes a newly created String object so that it represents an empty character sequence. 初始化一个新创建的String对象,使其代表一个空字符序列。 Note that use of this constructor is unnecessary since Strings are immutable. 注意,由于字符串是不可变的,因此不需要使用此构造函数。

Which matches your observed behavior. 符合您观察到的行为。

In java a default string or a string set as null has no value. 在Java中,默认字符串或设置为null的字符串没有值。 By setting a string with "" or with new String() it will create a new instance of the String class. 通过使用“”或new String()设置字符串,它将创建String类的新实例。 A string which is initiated with "" or new String() is just a String ready to be used. 以“”或new String()开头的字符串只是准备使用的字符串。 I guess you can think of it as a cup. 我想你可以把它当作杯子。 If something is null you have no cup, but if something, such as this string, is initiated as new String() or "" you now have an empty cup. 如果某物为null,则没有杯子,但是如果某物(例如此字符串)以new String()或“”的形式初始化,则您现在有一个空杯子。

Well, the string b is not null anymore because you created a String and assigned it to the variable. 好吧,字符串b不再为null ,因为您创建了一个String并将其分配给该变量。

If you use the default constructor of String , you will get an empty String : 如果使用默认的String构造函数,则会得到一个空String

public String() 公共String()

Initializes a newly created String object so that it represents an empty character sequence. 初始化一个新创建的String对象,使其代表一个空字符序列。 Note that use of this constructor is unnecessary since Strings are immutable. 注意,由于字符串是不可变的,因此不需要使用此构造函数。

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String() http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String()

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

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