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

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 thingking in java