Thursday, March 1, 2012

Challenge 048’s Solution

Of the three, only statements II and III are true. This is because of the difference between the == operator and the equals method. First, all three constructors successfully create String objects called s1, s2, and s3 that represent the string "crab". Next are the three statements. Statement I is true if “s1 == s2”. Both s1 and s2 equal the String value "crab"; however, the == operator doesn’t compare the values of s1 and s2, rather their addresses. Basically, it sees whether or not the two references are to the same object. s1 and s2 are two different objects; thus, the statement “s1 == s2” is false. Statement II is true if “s1.equals(s2)”. The equals method compares the values of s1 and s2. Both s1 and s2 equal the String value "crab"; thus, the statement “s1.equals(s2)” is true. Finally, statement III is true if “s3.equals(s2)”. Both s3 and s2 equal the String value "crab"; thus, the statement “s3.equals(s2)” is true.
 
−Phoenix

1 comment:

  1. Perfection. There is no doubt that you understand object references, and 200 XPs are awarded.

    ReplyDelete