tags:

views:

129

answers:

6

Hi all, My understanding of java String got wrong when i see this code. I am not sure how this is happening. Can anyone explain why is so?.

public class NewClass {
    public static void main(String[] args) {
        String str=null;

        System.out.println(str+"Added");
    }
}

output:nullAdded

A: 

String variable str is given the null value.

When you print it, the String#toString() converts that to the string 'null', and appends the string "Added". The result is

nullAdded
Jim Garrison
Thanks Jim,you are right.since we=hen i tried with creation an object of string,it gives only the Added as output.
vipin k.
The result is correct, but your explanation is wrong. There's no 'default toString()' method, which converts null references to the string "null".
jarnbjo
toString on which instance? The null reference? Nice try, but still wrong.
jarnbjo
+11  A: 

String concatenation treats a null reference as if it were "null" in Java. From the docs for StringBuilder.Append(String):

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.

Basically your code is similar to:

public class NewClass {
    public static void main(String[] args) {
        String str=null;

        System.out.println(new StringBuilder().append(str)
                                              .append("Added")
                                              .toString());
    }
}

Does that make it clearer?

Jon Skeet
+2  A: 

What happens is that when you use the + operator, both operands are converted to a string (if required) via String.valueOf method. This returns the four-character string "null" for a null reference, rather than an actual null reference.

Thus null + "Added" is equal to "null" + "Added" and hence "nullAdded".

Andrzej Doyle
Tony the Pony(...) is actually correct about the little details, it's not String.valueOf() but StringBuilder which causes the "null" to appear.
Esko
It depends what level of the stack you're looking at. In 1.5.0_06, at least, the StringBuilder implementation is return append(String.valueOf(obj)); which is why I listed valueOf as the method performing the null conversion. Arguably Jon's is more correct from an "interface" point of view, whereas I'd maintain mine is more correct from an "implementation" point of view; and I consider the latter more appropriate to this level of question.
Andrzej Doyle
Had to check, .append(Object obj) uses String.valueOf(obj); which internally is merely `return (obj == null) ? "null" : obj.toString();`, however .append(String str) copies characters directly. Meh, we're both right.
Esko
A: 

What you might want to do is initialise the string with the empty string:

String str = "";

Cheers

Tom

Tom Bartel
You mean String str = ""; as the '' is for chars.
AlBlue
Ah, thanks. It's been a while...
Tom Bartel
A: 

Java will/had always when concatanating a string converted null objects into the string null. via String.valueOf.

Java knows it is concatenating into a string, so even if the null is at the start (not at the end) of the expression it will still convert it to null.

you don't get a nullpointerException since no operation is called on the null object. A Little strange I know. but it is what it is.

link: concat null and String

jeff porter
A: 

With other words, you'd expect a NullPointerException here?

Well, the key is: the + is an operator, it is not a field or method of the String class. So there's no need to access the str reference.

You would only get NPE when you do something like

obj.someMethod();
// or
obj.someField;

while the obj is null.

BalusC