java 编程思想 第三章 练习14
2017-10-30 21:31
603 查看
编写一个接收两个字符串参数的方法,用各种布尔值的比较关系来比较这两个字符串,然后把结果打印出来。做==和!=比较的同时,用equal()作测试。在main()里面用几个不同的字符串对象调用这个方法。
public static void main(String[] args){ compare("hello", "hello"); compare("hello", new String("hello")); compare("hello", "kldsf"); } public static void p(String s, boolean b) { System.out.println(s + ": " + b); } private static void compare(String str1, String str2) { System.out.println("----------"+ str1 + "---------" + str2); p("str1 == str2", str2 == str1); p("str1 === str2", str2 == str1); p("str1 != str2", str2 != str1); p("str1 equal str2", str2.equals(str1)); }
The only comparisons that actually compile are == and !=. This (slightly tricky)
exercise highlights the critical difference between the == and != operators,
which compare references, and equals( ), which actually compares content.
Remember that quoted character arrays also produce references to String
objects. In the first case, the compiler recognizes that the two strings actually
contain the same values. Because String objects are immutable (you cannot
change their contents), the compiler can merge the two String objects into one,
so == returns true in that case. However, when you create a separate String s
you also create a distinct object with the same contents, therefore the == returns
false. The only reliable way to compare objects for equality is with equals( ).
Be wary of any comparison that uses ==, which always and only compares two
references to see if they are identical (that is, they point to the same object).
相关文章推荐
- 《Java 编程思想》--第三章:操作符
- Java 编程思想(第4版)学习笔记(各种容器(集合框架)的比较 Collection Map ..第11章 练习4)
- java 编程思想课后题(第三章)
- Java 编程思想(第4版)学习笔记(第11章 练习2 练习3 Arrays.asList() Colections.addAll())
- (36)21.3.6 并发 练习 15---Java编程思想之并发笔记
- Java 编程思想(第4版)学习笔记(迭代器 Iterator ListIterator 第11章练习11)
- 【Java编程思想 - 练习】吸血鬼数字
- java编程思想第11章练习16
- java编程思想---第三章(操作符)
- Java编程思想---第三章笔记
- (37)21.3.6 并发 练习 16---Java编程思想之并发笔记
- Java 编程思想(第4版)学习笔记(各种容器(集合框架)的比较 Collection Map ..第11章 练习4)
- java 编程思想 11章 持有对象 练习15
- java编程思想 第4章 练习9
- Java 编程思想(第4版)学习笔记(迭代器 Iterator ListIterator 第11章练习11)
- Java编程思想--第三章 操作符
- (41)21.4.1 并发 练习 17---Java编程思想之并发笔记
- 【JavaWeb-14】代理Proxy、动态代理、AOP编程思想、注解、元注解、类加载器
- Java基础编程思想学习 (第三章)三元函数
- java 编程思想的学习笔记 - 第三章 操作符 第四章 控制执行