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

标签 java null string-concatenation

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

相关文章:

java - 在 Java 代码中为 TextView 设置文本

java - 需要在 linux shell 命令中转义的字符列表

java - 与 Java 或其他非函数式语言相比,Scala 究竟如何利用更多的核心?

javascript - if (a) {} 抛出未捕获的 ReferenceError

excel - VBA宏在新列中连接2列

c# - 在 C# 中优化循环字符串连接的性能

elixir - 我可以在Elixir中连接字符串并使用管道运算符吗?

java - 当属性来自另一个表时,如何避免在 Spring Data JPA 上指定 SQL 查询

java - 当对象传递到多层时检查 null 的最佳方法是什么

php 如果 AND mysql 为空