您的位置:首页 > 编程语言 > Java开发

Java Puzzlers笔记--puzzle 13: Animal Farm 优先级以及对象引用问题

2007-03-04 11:00 537 查看
public class AnimalFarm{
 publi static void main(String[] args){
  final String pig = "length: 10";
  final Stirng dog = "length: " + pig.length();
  System.out.println("Animals are equal: " + pig==dog);
 }
}

Solution:

                显示:false

                因为 "Animals are equal: " + pig==dog实际上是("Animals are equal: " + pig)==dog;

                +的优先级比==的优先级高;

                而==两边都是用对象的地址作比较;

TID:

              The == operator, howerver, does not test whether two objects are equal; it tests whether two object references are identical.

               You may be aware that compile-time constants of type Stirng are interned. In other words, any two contant expressions of type String that designate the same character sequence are represented by identical object references.

                The + operator, whether used for addition or string concatenation, binds more tightly than the == operator.

                 When using the string concatenation operator, always parenthesize nontrivial operands.

Correctly:

                System.out.println("Animals are equal: " +  pig.equals(dog));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息