tags:

views:

223

answers:

8

Is there a difference between these ?

if(myString.equals("")){

}

if(myString.equals(null)){

}

if(myString == ""){

}

I have a string, I don't know is it empty or has some emtpy spaces I just wan't to stop it to be written in database if it is invalid(if empty or with some blank spaces).

+3  A: 

Yes there is.

First will return true if your string is empty.

Second will always return false.

Third will return true if your string is defined exactly like this:

String myString = "";

Note that this is not the same as case 1! The first tests for value equality, while the second for identity.

    String myString = "";
    String myOtherString = new String(myString);

    assert myString == "";
    assert myOtherString.equals("");
    assert myOtherString != "";

Bottom line is:

  • use the first case for comparisons between strings,
  • use myString == null for null tests,
  • never use the third one!
Péter Török
so there is no difference between 1 and 3 ?
Gandalf StormCrow
You should never use 3, objects such as Strings should be checked for equality with .equals. You should, however, use == to check if the String is null.
ColinD
+10  A: 

Each of your examples are different from each other.

  1. The first one is a simple compare to see if myString is empty (a string with no characters in it)
  2. The second is always either false or a NullPointerException
  3. The third checks to see if the variable myString references the empty string constant. That will be true if the variable is explicitly initialized from the empty string constant, or if the variable is initialized with some "generated" empty string (for example, new StringBuilder().toString()) and then explicitly added to the constant pool with intern().

As pointed out in a comment, the first example may also throw NullPointerException, but not the third.

Pointy
Nice, very concise:].
pajton
The second is always false - `equals` handles null parameters correctly.
Péter Török
@Péter Török: yes, equals is fine with nulls, but myString itself may be null, in which case there will indeed be a NullPointerException.
jjujuma
@jjujuma Yeah, sure. This has not much to do with the original question though. And if @Pointy had thought about this, I believe he would have mentioned the same in case 1 too.
Péter Török
Yes @Peter you're right! Case 1 can also be a null pointer exception; I noted it for case two because I always hedge after typing "always" (well, almost always)
Pointy
@Pointy sounds familiar - I also have a sinking feeling in my stomach whenever I am typing "always" or "never" here at SO :-) You could have made it more clear though that the `NullPointerException` is not related to `equals`, as the OP was focused on the usage of `equals`.
Péter Török
+5  A: 

To achieve what you want, write:

if (!myString.trim().equals("")) {
    // write to database
}

or if there is also a possibility that myString may be null:

if (myString != null && !myString.trim().equals("")) {
    // write to database
}
pajton
I don't think so. myString can be null so that would throw an NPE.
Freiheit
I specifically ommited the check for `null`, because OP said `I don't know is it empty or has some emtpy spaces`. But, maybe I'll add a version with check for `null` too.
pajton
@pajton hang on now, so if the string is empty it doesn't mean its null?
Gandalf StormCrow
@Gandalf It depends what you mean by 'empty'. `null` is `null`:-), `""` is empty `String`, `" \t \n "` is a `String` with empty spaces or more correctly whitespaces
pajton
@Gandalf In casual speech one might say that `null` is an empty `String` that wouldn't be exactly-technical-correct.
pajton
+2  A: 

pajton has added the correct answer. to clarify what's wrong with your attempts:

//true if myString is the empty string. will fail on " "  
if(myString.equals("")){

}

//always false, or fails
//if myString is null, you'll get a NullPointerException
//if it isn't, you'll get false
if(myString.equals(null)){

}

//a bad way to do things with unexpected results.
//when dealing with objects, == is true when each are the same object.
//two different objects that have the same content or value (e.g. clones)
//will return false using this technique
if(myString == ""){

}
z5h
A: 

String in Java is just another object. Your first comparison is the most correct one. It compares myString with a blank and will return true if your string is also empty (""). The second comparison is always false. The third, it compares the equality of objects (think of it as comparing the address of an object). I think will always return false unless your string is String myString = "" (not sure on this one).

Daniil
A: 

They are all distinct. Assuming myString is non-null,

  1. Will return true if the String referred to by myString represents an empty string
  2. Will always return false
  3. Will return true if myString happens to refer to the very same instance of String as "". This may well be true in your program, but may well be false too.
jjujuma
A: 

Just use Apache Commons StringUtils.isBlank()

EDIT: To achieve what you want using @zim2001's method do this:

if ( StringUtils.isNotBlank(myString) ) { 
    // write to database 
} 

This is much easier to read than the current accepted answer. (But please do see other posts here to learn the ins and outs of working with String.)

harschware
My guess is that he is beginning to learn programming, or at least java. Pointing him to an API instead of explaining what is happening is not the best teaching.
Decio Lira
there was already 4 posts teaching Java by the time I posted. I chose to "teach" an alternate method. There is always more than one way to skin a cat. Besides, see @zim2001 answer for the current best answer. Yes, best IMO, since it provides a more concise method and thus much easier to read, than the current accepted answer.
harschware
+1  A: 

If you don't bother to depend from external librairies, you could use apache commons StringUtils class, which provides a method named "isNotBlank()" which seems to perfectly suit your need :

Checks if a String is not empty (""), not null and not whitespace only.

StringUtils.isNotBlank(null)      = false
StringUtils.isNotBlank("")        = false
StringUtils.isNotBlank(" ")       = false
StringUtils.isNotBlank("bob")     = true
StringUtils.isNotBlank("  bob  ") = true

See http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.CharSequence%29

zim2001