This example is not quite true.  String objects are unique because duplicates
are stored as one in memory.  Therefore your example of a and b both being equal
to "abc" will be TRUE using "==".  This is because the "==" compares if the
pointer for each is equal and since they are both String objects, they are both
pointing to the same address in memory.  Your explanation holds true for any
object other than Strings.



















Chris Mcgarel wrote:

> Can someone expalin to a novice why I must use:
>          if (Request.Form("myFormElement").equals("myString"))
> rather than a straight comparison operator:
>         if (Request.Form("myFormElement")=="myString")
> ?
>
> The latter does not work for me even though both left and right sides of the
> statement are Strings.
>

It never will work, either, if your intent is to see if the string contents are
identical.  Strings are objects, not native data types.  When you use the "=="
operator on objects in Java, you are comparing the object references for
equality,
not the object contents.  That's why you need to use the equals() function to
accomplish what you want.

Given:

    String a = "abc";
    String b = "abc";

    if (a == b) {
        System.out.println("Got a == b");
    } else {
        System.out.println("Got a != b");
    }
    if (a.equals(b)) {
        System.out.println("Got a equals b");
    } else {
        System.out.println("Got a notequals b");
    }

will print

    Got a != b
    Got a equals b

The same principle applies to other object types besides Strings -- the equals()
method is used to compare the contents of two objects for equality, while the ==
operator compares the two pointers to those objects.

Craig McClanahan

===========================================================================
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

===========================================================================
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

Reply via email to