Well I'll be blowed!
Thanks Richard for picking me up on this one - I assumed both sides of the
|| would be evaluated before the || comparison itself.
But... you say Java translates x == y into x.equals(y). I don't think this
is right - try the following to see:
String x = new String("Harry");
String y = new String("Harry");
if(x == y) {
System.out.println("x == y");
} else {
System.out.println("x != y");
}
if(x.equals(y)) {
System.out.println("x has same value as y");
} else {
System.out.println("x has different value to y");
}
As far as I understand, x and y are references to objects, and x == y will
only be true if x and y refer to the same object.
Regards,
Mark
> -----Original Message-----
> From: Richard Clark [SMTP:[EMAIL PROTECTED]]
> Sent: Thursday, 6 January 2000 11:56
> To: [EMAIL PROTECTED]
> Subject: Re: Checking for null
>
> Look at my code again...
>
> if (null == s || s.length() == 0) ...
>
> Java translates x == y into x.equals(y). If I had said
> if (s == null)
> and s was null, you would get a null pointer exception. However, the
> constant null is handled specially -- it has an equals method that always
> works. Thus, saying
> if (null == s)
> will not fail with a null pointer exception.
>
> I also used the short-circuiting "or" operator || to connect the two
> pieces.
> In effect, a || b means "if a evaluates to false, evaluate b."
>
> In a case like this, || often leads to cleaner and more efficient code
> than
> nesting "if" statements.
>
> By the way, you could also say:
> if (null != s && s.length() != 0)
> which would yield the same result as Mark'code below.
>
> ...Richard
>
>
> -----Original Message-----
> From: Mark Foley [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, January 05, 2000 4:22 PM
> To: [EMAIL PROTECTED]
> Subject: Re: [SERVLET-INTEREST] Checking for null
>
>
> Hi,
>
> Wouldn't your conditional statement cause a null pointer exception if s is
> null? Try it!
>
> I do this:
> ...
> if(null != s) {
> if(s.length() != 0) {
> // it's not null and it's not empty
> }
> }
>
> Regards,
> Mark
>
> __________________________________________________________________________
> _
> To unsubscribe, send email to [EMAIL PROTECTED] and include in the
> body
> of the message "signoff SERVLET-INTEREST".
>
> Archives: http://archives.java.sun.com/archives/servlet-interest.html
> Resources: http://java.sun.com/products/servlet/external-resources.html
> LISTSERV Help: http://www.lsoft.com/manuals/user/user.html
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html