Why does a null value appear in string output?

后端 未结 4 1161
旧时难觅i
旧时难觅i 2020-12-04 02:49

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

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

/* N         


        
4条回答
  •  情深已故
    2020-12-04 03:01

    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

提交回复
热议问题