当字符串与 null 连接时会发生什么?

What happens when string is concatenated with null?

空运算符在字符串中的作用是什么, 连接时输出为 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

null 是分配给引用以指示对象不存在的“隐式”值。它不是运算符。

当您执行字符串和另一种类型的串联时,另一个值使用 String.valueOf(object) 简单地转换为其“字符串”表示形式并附加到第一个字符串。

例如:

"XYZ" + 1

=> "XYZ" + String.valueOf(1)

=> "XYZ" + "1"

=> "XYZ1"

同样,

"Jay" + null

=> "Jay" + String.valueOf(null)

=> "Jay" + "null"

=> "Jaynull"


在此处查看 String::valueOf(Object) 方法的实现。很明显,如果对象是 null,则字符串 "null" 应该 returned.

专业提示:尝试在 return 语句上放置一个断点,您将看到这段代码在 运行 一个带有字符串 + 对象的 java 程序中执行连接.

/**
 * Returns the string representation of the {@code Object} argument.
 *
 * @param   obj   an {@code Object}.
 * @return  if the argument is {@code null}, then a string equal to
 *          {@code "null"}; otherwise, the value of
 *          {@code obj.toString()} is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

希望对您有所帮助!