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

Discussion in 'Java' started by Matt, Jun 30, 2004.

  1. Matt

    Matt Guest

    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!!
     
    Matt, Jun 30, 2004
    #1
    1. Advertising

  2. On 29 Jun 2004 16:58:26 -0700, Matt wrote:

    > Is it an exception? or we
    > should still use equals method?


    b)
     
    Andrew Thompson, Jun 30, 2004
    #2
    1. Advertising

  3. Matt

    lukes Guest

    (Matt) wrote at Wt, 29 cze 2004 23:58:26 GMT:

    > 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

    --
    pozdrowka
    lukes
     
    lukes, Jun 30, 2004
    #3
  4. Matt

    Tom McGlynn Guest

    lukes wrote:
    > (Matt) wrote at Wt, 29 cze 2004 23:58:26 GMT:
    >
    >
    >>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
    >


    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
     
    Tom McGlynn, Jun 30, 2004
    #4
  5. Matt

    Roedy Green Guest

    On Wed, 30 Jun 2004 14:27:46 +0000 (UTC), lukes
    <> wrote or quoted :

    >>
    >> I saw people do both, but I don't know if == is ok?
    >>
    >> s.equals("")
    >> s == ""


    See http://mindprod.com/jgloss/gotchas.html#COMPARISON
    http://mindprod.com/jgloss/interned.html
    http://mindprod.com/jgloss/void.html


    for the full story.

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

    The safe way to do this is:


    if ( s != null && s.length() > 0 )
    {
    System.out.println( "non-void String" );
    }

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jun 30, 2004
    #5
  6. Tom McGlynn wrote:
    > 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
     
    John C. Bollinger, Jun 30, 2004
    #6
  7. John C. Bollinger <> scribbled the following:
    > Tom McGlynn wrote:
    >> 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.


    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("")).

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
    "Roses are red, violets are blue, I'm a schitzophrenic and so am I."
    - Bob Wiley
     
    Joona I Palaste, Jun 30, 2004
    #7
  8. Matt

    Roedy Green Guest

    On 30 Jun 2004 18:20:12 GMT, Joona I Palaste <>
    wrote or quoted :

    >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 ) )
    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jun 30, 2004
    #8
  9. Matt

    Hemal Pandya Guest

    Roedy Green <> writes:

    > On Wed, 30 Jun 2004 14:27:46 +0000 (UTC), lukes
    > <> wrote or quoted :
    >
    >>>
    >>> I saw people do both, but I don't know if == is ok?
    >>>
    >>> s.equals("")
    >>> s == ""

    >

    [....]
    >
    > 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";
    }
    ....
    }
     
    Hemal Pandya, Jul 1, 2004
    #9
  10. Matt

    Roedy Green Guest

    On Thu, 01 Jul 2004 07:57:19 -0700, Hemal Pandya
    <> wrote or quoted :

    >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

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 2, 2004
    #10
  11. Matt

    Roedy Green Guest

    On Thu, 01 Jul 2004 07:57:19 -0700, Hemal Pandya
    <> wrote or quoted :

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

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 2, 2004
    #11
  12. Matt

    Tony Morris Guest

    > 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
     
    Tony Morris, Jul 2, 2004
    #12
  13. Matt

    Tony Morris Guest

    "Roedy Green" <> wrote in message
    news:...
    > On Thu, 01 Jul 2004 07:57:19 -0700, Hemal Pandya
    > <> wrote or quoted :
    >
    > > 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.


    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
     
    Tony Morris, Jul 2, 2004
    #13
  14. Tony Morris wrote:
    > 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.
     
    Michael Borgwardt, Jul 2, 2004
    #14
  15. Matt

    Tony Morris Guest

    "Michael Borgwardt" <> wrote in message
    news:...
    > Tony Morris wrote:
    > > 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
     
    Tony Morris, Jul 4, 2004
    #15
  16. Tony Morris wrote:
    >>>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.
     
    Michael Borgwardt, Jul 4, 2004
    #16
  17. Matt

    Hemal Pandya Guest

    "Tony Morris" <> writes:

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


    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.
     
    Hemal Pandya, Jul 6, 2004
    #17
  18. Matt

    Tony Morris Guest

    "Hemal Pandya" <> wrote in message
    news:...
    > "Tony Morris" <> writes:
    >
    > >> 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.

    >
    > 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
     
    Tony Morris, Jul 7, 2004
    #18
  19. Matt

    Roedy Green Guest

    On Wed, 7 Jul 2004 10:24:37 +1000, "Tony Morris"
    <> wrote or quoted :

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

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 7, 2004
    #19
  20. Matt

    Tony Morris Guest

    "Roedy Green" <> wrote in message
    news:...
    > On Wed, 7 Jul 2004 10:24:37 +1000, "Tony Morris"
    > <> wrote or quoted :
    >
    > > 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.
    >
    > --
    > Canadian Mind Products, Roedy Green.
    > Coaching, problem solving, economical contract programming.
    > See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.


    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
     
    Tony Morris, Jul 7, 2004
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Edward A Thompson
    Replies:
    4
    Views:
    539
    Tony Morris
    Feb 11, 2004
  2. Matt
    Replies:
    5
    Views:
    16,439
    Roedy Green
    Jul 4, 2004
  3. Replies:
    28
    Views:
    14,001
  4. Smithers
    Replies:
    12
    Views:
    1,191
    Ben Voigt [C++ MVP]
    Jul 7, 2009
  5. javabeginner29
    Replies:
    0
    Views:
    409
    javabeginner29
    Apr 2, 2012
Loading...

Share This Page