开发者

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

开发者 https://www.devze.com 2022-12-29 18:53 出处:网络
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 J开发者_如何学Pythonava, I don\'t know whether it made a \

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 J开发者_如何学Pythonava, I don't know whether it made a " " string, or nulls are handled as blank lines.


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.


"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.


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.


It is initialized with "" ( empty string )

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

prints:

true


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 "".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号