Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a null value appear in string output?

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);
    }
}
like image 665
Manipal Avatar asked Nov 30 '22 19:11

Manipal


2 Answers

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).
like image 67
rgettman Avatar answered Dec 06 '22 09:12

rgettman


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.

like image 20
Warlord Avatar answered Dec 06 '22 11:12

Warlord