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.
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.
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.
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 "".
It is initialized with ""
( empty string )
public class StringTest {
public static void main( String [] args ) {
System.out.println( "".equals(new String()));
}
}
prints:
true