IT Notes‎ > ‎Java‎ > ‎Java Language‎ > ‎《Java 解惑》笔记‎ > ‎

Puzzle 13: Animal Farm

括号还是很重要的

——运算符的优先级暗藏陷阱

以下代码:
        final String pig = "length: 10";
        final String dog = "length: " + pig.length();
        System.out.println("Animals are equal: " + pig == dog);
执行后输出什么?是下面二者之一么?
  1. Animals are equal: true
  2. Animals are equal: false
都不是, 只输出一行
  • false
因为字符串连接符+的运算优先级高于比较符号==
"Animals are equal: " + pig == dog 其实和 ("Animals are equal: " + pig) == dog 等价.



  1. JLS 15.28 Constant Expression
  2. JLS 16.28 这个书上给的貌似有问题, 没有这一节的.
  3. Puzzle 11: The Last Laugh
Comments