2

Possible Duplicate:
Concatenating null strings in Java

Please find below the code snippet

String str = null;
str = str + "hi";

System.out.println(str)

The output of the above code is nullhi.

I thought the output will be hi, so kind of surprised with the output and not able to find the reason behind it.

Can someone please explain it.

2
  • 4
    It took me just 5 seconds to get that link of the post. Please use Google on regular basis. Commented Oct 30, 2012 at 18:10
  • i wasn't sure about the text to be used for google search, so directly posted here. Commented Oct 30, 2012 at 18:14

6 Answers 6

4

This is because append method. + gets converted as either StringBuilder or StringBuffer append operations.

public AbstractStringBuilder append(String str) {
if (str == null) str = "null";

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

Below is the generated byte code for your program

 0  aconst_null
 1  astore_1 [str]
 2  new java.lang.StringBuilder [16]
 5  dup
 6  aload_1 [str]
 7  invokestatic java.lang.String.valueOf(java.lang.Object) : java.lang.String [18]
10  invokespecial java.lang.StringBuilder(java.lang.String) [24]
13  ldc <String "hi"> [27]
15  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [29]
18  invokevirtual java.lang.StringBuilder.toString() : java.lang.String [33]
21  astore_1 [str]
22  getstatic java.lang.System.out : java.io.PrintStream [37]
25  aload_1 [str]
26  invokevirtual java.io.PrintStream.println(java.lang.String) : void [43]
29  return

So your code actully gets transformed into append(null) and then append("hi") which is why you get such output

Also it is clearly documented in 15.18.1. String Concatenation Operator +

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

Sign up to request clarification or add additional context in comments.

2 Comments

These are good and fun facts, but the true reason for OP's observation lies not with compiler implementation details, but with the JLS that clearly specifies the semantics of the concatenation operator.
@MarkoTopolnik Your comments always add to my knowledge. Added such reference from JLS
3

From JLS.

http://docs.oracle.com/javase/specs/jls/se7/html/index.html

§15.18.1. String Concatenation Operator + (reference)

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run-time.

§5.1.11. String Conversion (reference)

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Comments

1

null is the value printed if you try to print a null reference in java.

Comments

1

When you concatenate values together that are not all strings, those that are not are converted as if by String.valueOf. String.valueOf(null) is the string "null".

5 Comments

But str is a String, so this doesn't explain it.
null is not a String (indeed it is not any object).
Do you mean to imply that the compiler makes code that dynamically checks whether to use String.valueOf? Your implication is false: String.valueOf is always called for all reference-typed arguments to +.
Fair point, I was trying to describe the effect, not the mechanism.
The description of effect is also simpler if you just say "all operands are transformed as if by String.valueOf."
0

That was a decision that the creators of Java made early on. Any null value that is concatenated to a string will be output as null. This sort of makes sense if you imagine that you are trying to output a log message:

String personName = null;
System.out.println("Person name is: " + personName);

Result:

Person name is: null

That behavior can help you when debugging because you know that the variable was actually null (as opposed to an empty string, e.g.).

They could have chosen to simply throw an exception when you tried to do this, but that would have caused a lot of things to break even when doing something like building a log message or exception string.

They could also have done as you expected and made null values get output as an empty string. This is what the .NET framework does. But ultimately, that's not what they decided to do.

Comments

0

In the example shown by you you are concatenating the string null with hi so the output generated is
nullhi

String str = null;
str = str + "hi";

System.out.println(str);


as str=str+"hi "//shows one string is concatenating with the other

so the output you get is right.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.