See more remarks below :-)
> > -----Ursprüngliche Nachricht-----
> > Von: John Baker [mailto:[EMAIL PROTECTED]]
> > Gesendet: Donnerstag, 9. August 2001 09:55
> > An: [EMAIL PROTECTED]
> > Betreff: Re: Using Tomcat with MSAccess
>
> <snip />
>
> > > "".equals(passwd)
> > > rather than
> > > passwd.equals( "" )
>
> <snip />
>
> > No you shouldn't. That's totally evil. For a start, you're
> > creating another String object by doing ""
>
> <snip/>
> <remark>
> As "" is a constant string, it is created just once. So there
> is not much overhead. ("".equals might be even faster, because
> the jit can inline the method call, as the address of the object
> and the equals method is constant in this case.
It involves a comparison. The equals method is still called. I suspect a
length() is quicker.
You haven't defined "" as a static final constant, therefore a clever
compiler (which should be all compilers, but still) would realise this was a
constant. But it hasn't been defined a such so someone writing a compiler
doesn't have to treat it as such.
> </remark>
>
> > and to add to this, you're saying it's ok to pass null to
> > equals. Passing null to the equals method is an awful idea.
>
> <remark>
> Why ? "".equals(null) returns false, that what you wan't
> in most cases. (That return value is not implementation
> specific, it's granted by the API.)
>
> </remark>
Because the API doesn't say the method likes nulls. And getting into the
habit of passing nulls to objects is a bad thing to get into the habit of
doing.
>
> > You actually want:
> >
> > if ((passwd != null) && (passwd.lenght() == 0)) {
> > // Then do something
> > }
>
> <snip/>
> <remark>
> That's wrong, to be equivalent to ("".equals(passwd))
> it should be:
>
> if ((passwd == null) || (passwd.lenght() == 0)) {
> // Then do something
> }
> </remark>
Err, no, it's correct.
String s = null;
if ("".equals(s))
{
moo();
}
will not result in moo being executed. So now we've concluded that false is
returned from equals when null is passed, then your code extract will 'do
something' when passwd is null. And is therefore wrong.
if ((passwd != null) && (passwd.lenght() == 0))
is required to see if a String 's' is equal to "".
You were right when you said "".equals(passwd) was better than
passwd.equals("") as passwd could be null. And if passwd was null then the if
wouldn't get executed. However:
if ((passwd == null) || (passwd.lenght() == 0))
definitely does not replicate:
if ("".equals(passwd))
--
John Baker, BSc CS.
Java developer, Linux lover.
I don't wanna rock, DJ.