Think in java 答案_Chapter 3_Exercise 6

来源:互联网 发布:2016成都进出口数据 编辑:程序博客网 时间:2024/04/28 11:04

阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx

/****************** Exercise 6 ******************
* Write a function that takes two String
* arguments, and uses all the boolean
* comparisons to compare the two Strings and
* print the results. For the == and !=, also
* perform the equals() test. In main(), call
* your function with some different String
* objects.
***********************************************/

public class E06_CompareStrings {
  public static void p(String s, boolean b) {
    System.out.println(s + ": " + b);
  }
  public static void
  compare(String lval, String rval) {
    //! p("lval < rval: " + lval < rval);
    //! p("lval > rval: " + lval > rval);
    //! p("lval <= rval: " + lval <= rval);
    //! p("lval >= rval: " + lval >= rval);
    p("lval == rval", lval == rval);
    p("lval != rval", lval != rval);
    p("lval.equals(rval)", lval.equals(rval));
  }
  public static void main(String[] args) {
    compare("Hello", "Hello");
    String s = new String("Hello");
    compare("Hello", s);
    compare("Hello", "Goodbye");
  }
}

//+M java E06_CompareStrings

 

**This is a bit of a trick question, because the only comparisons that actually compile are == and !=. But it also points out the important difference between the == and != operators, which compare references, and equals( ), which actually compares content.

**The output of this program is:

lval == rval: truelval != rval: falselval.equals(rval): truelval == rval: falselval != rval: truelval.equals(rval): truelval == rval: falselval != rval: truelval.equals(rval): false

**Remember that quoted character arrays also produce references to String objects. In the first case, the compiler is smart enough to recognize that the two strings actually contain the same values. Because String objects are immutable – you cannot change their contents – the compile can merge the two String objects into one. This is why == returns true in that case. However, when a separate String s is created, even though it has the same contents, a distinct object is created and therefor the == returns false. The only reliable way to compare objects for equality is with equals( ); be wary if you see a comparison using ==, which always compares to see if two references are identical (that is, whether they point to the same object).