4

When I execute the following code the output is "nullHelloWorld". How does Java treat null?

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str=null;
        str+="Hello World";
        System.out.println(str);
    }
}
1
  • +1: Fancy abuse of the String concatenation rules :) I didn't know that. Commented Feb 19, 2014 at 22:28

4 Answers 4

12

You are attempting to concatenate a value to null. This is governed by "String Conversion", which occurs when one operand is a String, and that is covered by the JLS, Section 5.1.11:

Now only reference values need to be considered:

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Sign up to request clarification or add additional context in comments.

1 Comment

For those who are here searching a way to get rid of this null at start, simple way around would be initializing your variable with empty string "" rather then null.
7

When you try to concat null through + operator, it is effectively replaced by a String containing "null".

A nice thing about this is, that this way you can avoid the NullPointerException, that you would otherwise get, if you explicitly called .toString() method on a null variable.

Comments

0

Java treats null as nothing, it is the default value of a String. It appears in your String output because you use += to add "Hello World" to str.

String str=null;
str+="Hello World";
System.out.println(str);

You are basically telling Java: give my str variable the type of String and assign it the value null; now add and assign (+=) the String "Hello World" to the variable str; now print out str

Comments

0

my two cent:

    String str = null;
    str = str.concat("Hello World"); // Exception in thread "main" java.lang.NullPointerException

but

str += "Hello World";
System.out.println(str); // Hello World

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.