| Summary |
The == operator appears to show two different objects to be equal. |
| Background |
A common mistake for beginning Java programmers is using the == operator to test
the logical equality of two objects, for example, the values of two strings. This doesn't work, because
the == operator actually tests the equality of the reference variables, that is, if the two variables
are referring to the same object. To test the logical equality, that is, the equality of the object's state, we
normally use the equals() method.In the program below, we create three String objects, whose values are all equal. However,
the method of constructing the strings differs. We find that the == operator reports two of them to be
the same, but two others to be different.
|
| The Program |
public class Equality
{
public static void main (String[] args)
{
String s1 = "Hello, world!";
String s2 = "Hello, " + "world!";
String s3 = "Hello, ";
s3 += "world!";
System.out.println(s1 == s2);
System.out.println(s1 == s3);
}
}
|
| The Output | The program output is:true |
| The Challenge! | Explain this behavior. |