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

时间:2016-10-08 04:40:04

标签: java null string-concatenation

字符串中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);
}

这里发生了什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

与其他人提到的一样,../web/uploads/img是一个值。类似于说null是整数类型的值,或1是String类型的示例。

当你执行字符串和另一种类型的连接时,另一个值只是转换为它的"字符串"表示并附加到第一个String。

例如:

"XYZ"

成为

"XYZ" + 1

类似地,

"XYZ1"

变为

"Jay" + null 

底线是"Jaynull" 只是一个值。而不是运营商。它是一个隐含值,表示没有对象。

希望这有帮助!

相关问题