【问题标题】:Java: Unexpected behaviour with concatenating a String and an expression using the plus + operatorJava:使用加号 + 运算符连接字符串和表达式时出现意外行为
【发布时间】:2015-03-04 13:17:38
【问题描述】:

考虑下面这段代码

public class Test {
   public static void main(String... strings) {
      System.out.println("String, " + false);
      System.out.println("String, " + getFalse());
      System.out.println("String, " + new TestClass());
      System.out.println("String, " + (new TestClass() == null));
      System.out.println("String, " + new TestClass() == null);
   }

   private static class TestClass {
      public String toString() {
         return "false";
      }
   }

   private static boolean getFalse() {
      return false;
   }
}

为什么最后一个System.out.println 打印的输出与其他输出不同?我不知道,这是一个错误吗?它与加号运算符有关吗?字符串生成器?

【问题讨论】:

标签: java string operator-keyword behavior


【解决方案1】:

"String, " + new TestClass() == null

将被视为

("String, " + new TestClass()) == null

因此打印出false

(您可以在operator precedence查看更多详细信息)

【讨论】:

  • @user3649372 很高兴有帮助,您可以单击投票箭头下方左侧的勾号(复选标记)。我想你以前做过:p
猜你喜欢
  • 2021-02-20
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多