compare with empty string uses equals method or == ??

M

Matt

I know when we do Java string comparision, we should use equals method.
But how about compare with an empty string? Is it an exception? or we
should still use equals method?

I saw people do both, but I don't know if == is ok?

s.equals("")
s == ""

please advise. thanks!!
 
L

lukes

I know when we do Java string comparision, we should use equals method.
But how about compare with an empty string? Is it an exception? or we
should still use equals method?

I saw people do both, but I don't know if == is ok?

s.equals("")
s == ""

please advise. thanks!!

Its the same thing like with other String checks

you can check if String is empty by: str.equals("") or str.length() == 0
 
T

Tom McGlynn

lukes said:
Its the same thing like with other String checks

you can check if String is empty by: str.equals("") or str.length() == 0

For the OP, as discussed many times before the '==' is not the same
as equals. I.e.,

String x = new String("");
String y = new String("");

x == y != x.equals(y)


As to whether to use .equals or .length, I think they tend to emphasize
subtly different things. If I consider "" to be a valid string
(perhaps one of a specific set like "yes", "y" and "") then I might tend to use .equals.
On the other hand if I'm growing a string and I'm checking to see
if I've put anything in the string so far, then I'd probably use .length.

One last reminder to the OP: be careful of the case where
the string you are checking is null.

After String x = null; neither x.equals("") or x.length()

are likley to be do what you want!


Regards,
Tom McGlynn
 
J

John C. Bollinger

Tom said:
One last reminder to the OP: be careful of the case where
the string you are checking is null.

After String x = null; neither x.equals("") or x.length()

are likley to be do what you want!

But "".equals(x) might do.

It is a sometimes useful feature of Java that String literals represent
perfectly normal runtime String instances, and that therefore you make
invoke any of String's methods on them. Read the docs for
String.equals() to figure out the difference between x.equals("") and
"".equals(x). Hint: it has to do with the case described above.


John Bollinger
(e-mail address removed)
 
J

Joona I Palaste

But "".equals(x) might do.
It is a sometimes useful feature of Java that String literals represent
perfectly normal runtime String instances, and that therefore you make
invoke any of String's methods on them. Read the docs for
String.equals() to figure out the difference between x.equals("") and
"".equals(x). Hint: it has to do with the case described above.

This is why I always use "".equals(x) when x could be null, and x being
null is to be taken as failure, not success. However I don't think
there's an easier way to test that x is both non-null and *not* equal
to "" than if (x!=null && !x.equals("")).
 
R

Roedy Green

there's an easier way to test that x is both non-null and *not* equal
to "" than if (x!=null && !x.equals("")).

if ( x != null && x.length() > 0 )

is an alternative. You could experiment to see which is more
ram-efficient, faster, generates more compact class file etc.

you might even encapsulate that with a static final inlined method:

if ( useful( x ) )
 
H

Hemal Pandya

Roedy Green said:
[....]

The second form is faster, but only works reliably if s is interned.

I usually declare my 'public static final's to as String rather then
int for a somewhat safe usage, as a compromise in absence of enums. I
would appreciate any comments you may have on this scheme.

public class Foo{
public static final ONE = "one";
public static final TWO = "two";
public void bar(String param){
if (param != ONE && param != TWO)
throw new RuntimeError "Parameter must be one of Foo_ONE, Foo.TWO";
}
....
}
 
R

Roedy Green

public class Foo{
public static final ONE = "one";
public static final TWO = "two";
public void bar(String param){
if (param != ONE && param != TWO)
throw new RuntimeError "Parameter must be one of Foo_ONE, Foo.TWO";
}
....

Java 1.5 enums is the way to fly starting soon. It beats all the old
hacks.

see http://mindprod.com/jgloss/enum.html
 
R

Roedy Green

public static final ONE = "one";
public static final TWO = "two";
public void bar(String param){
if (param != ONE && param != TWO)

A way you can get a sort of quasi type safety you see in the AWT with
the GridBag constants. Different types of enums are given different
RANGES of values. Then you can check that the right sort of enum
constant was given with a simple check of this form:


if ( ! (SMALLEST_FRUIT <= fruit && fruit <= BIGGEST_FRUIT) )
{
throw new IllegalArgumentException ( "fruit " + fruit + " not a valid
fruit enumerated type." );
}


You assign each of your enums non-overlapping but dense ranges.
 
T

Tony Morris

I usually declare my 'public static final's to as String rather then
int for a somewhat safe usage, as a compromise in absence of enums. I
would appreciate any comments you may have on this scheme.

Comment: poor form.
Investigate the Type-safe enumeration design pattern.

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 
T

Tony Morris

Roedy Green said:
A way you can get a sort of quasi type safety you see in the AWT with
the GridBag constants. Different types of enums are given different
RANGES of values. Then you can check that the right sort of enum
constant was given with a simple check of this form:


if ( ! (SMALLEST_FRUIT <= fruit && fruit <= BIGGEST_FRUIT) )
{
throw new IllegalArgumentException ( "fruit " + fruit + " not a valid
fruit enumerated type." );
}


You assign each of your enums non-overlapping but dense ranges.

There is more to the issue than just type safety.

In your example, you have immediate runtime failure in the event of a
misuse.
The alternative without the check is some indeterminate behaviour - allowing
the application to carry on with a bad value.

More preferred is compile-time failure, which is provided by the type-safe
enumeration design pattern.
A further issue is the fact that a "public static final int [or other
appropriate type - JLS 15.28]" that is not "lazily initialised" is a
compile-time constant.
This presents issues in versioning, which has consequences in such things as
serialization, blah, blah (I think everyone knows about this particular
problem so I won't repeat it).
The type-safe enumeration design pattern eliminates this problem.

J2SE 1.5.0 (JSR-201) accomplishes "enums" by using a type-safe enumeration
implementation.
i.e. it is just "language candy" to the more long-hand, yet still robust,
implementation.

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 
M

Michael Borgwardt

Tony said:
A further issue is the fact that a "public static final int [or other
appropriate type - JLS 15.28]" that is not "lazily initialised" is a
compile-time constant.
This presents issues in versioning, which has consequences in such things as
serialization, blah, blah (I think everyone knows about this particular
problem so I won't repeat it).
The type-safe enumeration design pattern eliminates this problem.

Actually, it's just as bad in that regard.
 
T

Tony Morris

Michael Borgwardt said:
Tony said:
A further issue is the fact that a "public static final int [or other
appropriate type - JLS 15.28]" that is not "lazily initialised" is a
compile-time constant.
This presents issues in versioning, which has consequences in such things as
serialization, blah, blah (I think everyone knows about this particular
problem so I won't repeat it).
The type-safe enumeration design pattern eliminates this problem.

Actually, it's just as bad in that regard.

No it isn't.
Please elaborate on your "apparant misunderstanding".

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 
M

Michael Borgwardt

Tony said:
A further issue is the fact that a "public static final int [or other
appropriate type - JLS 15.28]" that is not "lazily initialised" is a
compile-time constant.
This presents issues in versioning, which has consequences in such things as
serialization, blah, blah (I think everyone knows about this particular
problem so I won't repeat it).
The type-safe enumeration design pattern eliminates this problem.

Actually, it's just as bad in that regard.


No it isn't.

Right, it's in fact worse.

Whereas an int constant can be serialized directly and incurs versioning
problems only if the version changes are done badly, a simple (pre-1.5)
typesafe enum *invariably* breaks when serialzed, unless you put the
oh-so-inferior int constants under the hood and do custom deserialization.
 
H

Hemal Pandya

Tony Morris said:
Comment: poor form.
Investigate the Type-safe enumeration design pattern.

Which type-safe enumeration design patterns are you referrning to? I
know of only one with some choices in implementation (one object per
element or one type per element).

What makes you think I don't know about it? I was talking about a
lightweight alternative; type-safe enumeration, the way it is
usually described is too much code for too little syntactic sugar.
 
T

Tony Morris

Hemal Pandya said:
Which type-safe enumeration design patterns are you referrning to? I
know of only one with some choices in implementation (one object per
element or one type per element).

Not this:

// YUK!
interface Names
{
String TONY = "Tony";
String HEMAL = "Hemal";
}

But this:

// Type-safe enum - much nicer.
class Name
{
// the only two possible instances.
public static final Name TONY = new Name("Tony");
public static final Name HEMAL = new Name("Hemal");

private String n;

// important - outside construction is not possible
private Name(String n)
{
this.n = n;
}

public String toString()
{
return n;
}
}

Of course there are derivations of this idea e.g. protected constructors for
subclassing, implementing the java.io.Serializable interface.
What makes you think I don't know about it? I was talking about a
lightweight alternative; type-safe enumeration, the way it is
usually described is too much code for too little syntactic sugar.

The way it is described is additional code and a slight performance hit for
more robust and maintainable software.
I (almost) always sacrifice performance for maintainability - it costs less
for a hardware upgrade than maintaining poorly written software.

Perhaps you did know about it?
Your suggestion implied (with asumption of course) the contrary.

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 
R

Roedy Green

public static final Name TONY = new Name("Tony");
public static final Name HEMAL = new Name("Hemal");

I think you are going to have to sell this a little harder. It is
obviously more gobblegegook. Just what do you get back?

Why is this easier to maintain?

I am not disagreeing, just prompting a deeper explanation.
 
T

Tony Morris

Roedy Green said:
I think you are going to have to sell this a little harder. It is
obviously more gobblegegook. Just what do you get back?

Why is this easier to maintain?

I am not disagreeing, just prompting a deeper explanation.

Consider the following method:

void m(String name);

As it stands, a client might just pass in anything, but really you must pass
in one of the two defined names in the example.
Clients (usually customers or users of your API) almost always try to pass
in some incorrect value before reading the documentation.
As it currently stands, you'd have a runtime check i.e. you'd fail with an
IllegalArgumentException (or something) if the wrong value was passed.

Preferred is a compile-time check which restricts the values.

void m(Name n);

In this case, you are guaranteed at compile-time to receive a correct value.
This is one of a few advantages and the triviality of this example does not
highlight how important this particular advantage actually is.
Joshua Bloch gives a very good explanation in his book "Effective Java
Programming" and this specific article happens to be in a publicly available
sample chapter.

http://java.sun.com/docs/books/effective/chapters.html
Chapter 5


--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top