[Divunal-devel] Re: == != .equals()

James Knight jknight@MIT.EDU
Fri, 9 Jul 1999 15:52:38 -0400


I thought this was interesting...the fact that .intern() _doesn't always
work_ is somewhat odd. :)

>> Um, OK - that'll work because the compiler can detect they're both
>> String constants and the compiler will represent them as a single object
>> for efficiency.
>>
>> Consider this:
>> public class StringTester {
>>
>>
>> public static void main(String [] argv) {
>>
>>
>>  String s = "foobar";
>>
>>  StringBuffer sb = new StringBuffer("foo");
>>  sb.append("bar");
>>
>>  String t = sb.toString();
>>
>>  System.out.println(s == t);
>>  System.out.println(s.equals(t));
>>
>>
>>  s = s.intern();
>>  t = t.intern();
>>
>>  System.out.println(s == t);
>>  System.out.println(s.equals(t));
>>
>>
>> }
>>
>> output:
>> false
>> true
>> true
>> true
>>
>>
>> The first one return's false because the two string's definately aren't
>> the same object (==) but they are equal (equals())
>
>Well I'll be d***ed. I never noticed that before. Since I tend to use
>.equals() anyway -- or in the case of strings .equalsIgnoreCase() -- I
>"assumed" that all of the text book code was correct. And yes, I am aware
>of what assumptions are ;)
>
>I just ran your example in VisualAge for Java (IBM's IDE) just to see if
>there was a difference. The output was:
>
>false
>true
>false
>true
>
>> So clearly == is not equivalent to .equals() for Strings in anything
>> except carefully constructed examples where you know that they are the
>> same object.
>
>True enough... I stand corrected. I also thought it was interesting that
>.intern() did not behave consistently across VM implementations.

--
You are in a maze of testy little Java VMs, all subtly different.