> String str1="Hello";
> String str2="Hello";
> if(str1==str2) {
> System.out.println("str1==str2");
> }
> if(str1.equals(str2)) {
> System.out.println("str1.equals(str2))");
> }
>
> The two "if conditions" are true although the two String objects are
> located into two different memory addresses.
Not to beat this subject to death, but in this case the two instances
*are* at the same address. The compiler is smart enough to place the
String "Hello" into the constant pool, and both str1 and str2 will be
initialized with that same value. If the example is modified:
String str1=new String("Hello");
String str2=new String("Hello");
Then the two strings will be at different addresses, and the first
test will fail. Likewise for:
String str1=argv[0];
String str2=argv[1];
even if the arguments happen to be identical.
I should qualify this by saying that this is under the Java 2
reference implementation on Solaris. It's certainly possible that
some other implimentation overloads == on strings, but if it does it's
not compliant.
(BTW, for those who know Lisp or Scheme, this is exactly the
difference between eq? and equals?)
- Larne
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
FAQs on JSP can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html