delete
delete

Reputation:

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

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.

Upvotes: 17

Views: 49546

Answers (5)

OscarRyz
OscarRyz

Reputation: 199215

It is initialized with "" ( empty string )

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

prints:

true

Upvotes: 4

someguy
someguy

Reputation: 7334

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

Upvotes: 1

Jay
Jay

Reputation: 27464

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.

Upvotes: 4

DJClayworth
DJClayworth

Reputation: 26856

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

Upvotes: 8

Chris Dennett
Chris Dennett

Reputation: 22721

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.

Upvotes: 24

Related Questions