简体   繁体   中英

Default value of Java String: null vs “”

The default value of a Java String is '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,

Initializes a newly created String object so that it represents an empty character sequence. 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. By setting a string with "" or with new String() it will create a new instance of the String class. A string which is initiated with "" or new String() is just a String ready to be used. 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.

Well, the string b is not null anymore because you created a String and assigned it to the variable.

If you use the default constructor of String , you will get an empty String :

public String()

Initializes a newly created String object so that it represents an empty character sequence. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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