Java Reference
In-Depth Information
String nickname = name.substring(0, 3);
. . .
if (nickname == "Rob") // Test is false
This is a particularly distressing situation: The wrong code will sometimes do
the right thing, sometimes the wrong thing. Because string objects are always
constructed by the compiler, you never have an interest in whether two string
objects are shared. You must remember never to use == to compare strings.
Always use equals or compareTo to compare strings.
5.2.4 Comparing Objects
If you compare two object references with the == operator, you test whether the
references refer to the same object. Here is an example:
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
The comparison
box1 == box2
is true . Both object variables refer to the same object. But the comparison
box1 == box3
is false . The two object variables refer to different objects (see Figure 4 ). It does
not matter that the objects have identical contents.
Search WWH ::




Custom Search