字符串中空运算符的作用是什么, 连接时输出为 null+string 为什么? prg 是。
public static void main2()
{
String s1=null;
String s2="";
System.out.println(s1);
System.out.println(s2);
s1=s1+"jay";
s2=s2+"jay";
System.out.println(s1);
System.out.println(s2);
}
这里发生了什么?
最佳答案
null
不是运算符。 null
是一个表示 null
引用的文字,该引用不引用任何对象。 null
是引用类型变量的默认值。这意味着字符串变量或另一个对象类型变量没有指向内存中的任何位置。
当你将它与另一个字符串连接时。它将添加到该字符串中。为什么?因为如果引用为 null
,则会将其转换为字符串 "null"
。
String s1=null;
String s2="";
System.out.println(s1);
System.out.println(s2);
s1=s1+"jay";
s2=s2+"jay";
// compiler convert these lines like this,
// s1 = (new StringBuilder()).append((String)null).append("jay").toString();
// s2 = (new StringBuilder()).append((String)"").append("jay").toString();
System.out.println(s1);
System.out.println(s2);
它将打印nulljay
关于java - 当字符串与 null 连接时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928741/