Why is the string displaying a null value?

When I execute the following code, the output will be "nullHelloWorld". How does Java handle 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);
    }
}
+3
source share
3 answers

You are trying to combine a value null. This is defined by the "String Conversion" which occurs when one operand is String, and which is covered by JLS, section 5.1.11 :

Now you need to consider only the reference values:

  • If the link is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
+12
source

null +, String, "null".

, NullPointerException, , .toString() null.

+6

Java null , String. String, += "Hello World" str.

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

Basically you say Java: pass the strtype to the variable Stringand assign it a value null; now add and assign ( +=) String"Hello World" to the variable str; print nowstr

0
source

All Articles