java - 对字符串和 null 关键字的 Concat 操作

标签 java string null concat

据我了解,当 + 运算符与两个字符串文字一起使用时,会调用 concat 方法来生成预期的字符串。 示例 - String s = "A"+ "B";

当有空值代替下面的一个文字时,它会生成下面的输出。 我在这里很困惑 - 为什么它不抛出 NullPointerException

    String str = null + "B";
    System.out.println(str);

输出:

nullB

最佳答案

why it is not throwing NullPointerException.

因为,字符串连接将字符串转换操作应用于非String类型的操作数,在本例中为null引用。字符串连接转换为:

String str = new StringBuilder("null").append("B").toString();

不会抛出 NPE

来自 JLS §5.1.11 - String Conversion :

This reference value is then converted to type String by string conversion. [...]

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

关于java - 对字符串和 null 关键字的 Concat 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19300193/

相关文章:

java - 在 Mongo 中插入 JSON

java - Selenium WebDriver 和 Highchart 测试

java - spring boot 图片显示url

java - 为什么允许抽象类 "DocumentBuilderFactory"实例化新实例

java - 存储数字输入 - 为什么 Java Scanner nextInt() 允许 "invalid"零填充整数?

C 在函数之间传递字符串

JSF 登录过滤器, session 为空

php - 在 PHP 脚本中 MySQL 查询返回 NULL 列

C:使用 scanf 之前计算字符串的长度

java - 分配的最终对象字段在构造函数中可能仍然为 null 是真的吗?