views:

172

answers:

5

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.

+8  A: 

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.

Chris Dennett
Thank you for the help brother. Where did you find that String() constructor code? I'd like to research some of the other base types in Java as well instead of asking 7 questions for each type.
Serg
If you have the JDK installed, it'll be somewhere like C:\Program Files\java\jdk1.7.0\src.zip. Eclipse finds this automatically so all I have to do is ctrl-click on String :)
Chris Dennett
The documentation for String explicitly states that String() creates an empty String. http://java.sun.com/javase/6/docs/api/java/lang/package-summary.html and click on String.
DJClayworth
Looking inside Java source code to answer this question is missing the point. This is a question of basic Java lang concepts.
leonbloy
+6  A: 

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

DJClayworth
+3  A: 

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.

Jay
+1  A: 

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

someguy
+1  A: 

It is initialized with "" ( empty string )

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

prints:

true
OscarRyz