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));
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));
相关文章推荐
- Java Puzzlers笔记--puzzle 14: Escape Rout (")双引号的问题
- Java Puzzlers笔记--puzzle 5: The joy of Hex 十六进制计算问题
- Java Puzzlers笔记--puzzle 19: Classy Fire 注释问题
- Java Puzzlers笔记--puzzle 15: Hello Whirled -Unicode字符问题
- Java Puzzlers笔记--puzzle 17: Huh? 转义字符问题
- Java Puzzlers笔记--puzzle 7: Swap Meat ^符号问题
- Java Puzzlers笔记--Puzzle 2: Time for a change 关于浮点型的问题
- Java Puzzlers笔记--puzzle 8: Dos Equis 选择操作符问题
- Java Puzzlers笔记--puzzle 9: Tweedledum +=的问题
- Java Puzzlers笔记--Puzzle 3: Long Division 溢出问题
- Java Puzzlers笔记--puzzle 10: Tweedledee += 问题(2)
- Java Puzzlers笔记--puzzle 21: What's my Class, take 2 路径字符问题
- Java关于对象引用问题
- (java)对象引用向上转型后,无法调用子类独有的方法和属性问题
- java序列化的引用问题以及将transitent的序列化方法
- java学习笔记---第一个applet程序以及一个小问题的解决
- Java学习笔记----你可能不知道那些知识,对象复制与引用
- JAVA学习笔记2---static、new、final以及java引用的实质
- Android(java)学习笔记70:同步中的死锁问题以及线程通信问题
- java的库、包、编辑单元、类,以及系统库和第三方库的引用问题。