When "" == s is false but "".equals( s ) is true

OscarRyz picture OscarRyz · Jul 10, 2009 · Viewed 19.6k times · Source

EDIT Thanks for the prompt responses. Please see what the real question is. I have made it bold this time.

I do understand the difference between == and .equals. So, that's not my question (I actually added some context for that)


I'm performing the validation below for empty strings:

if( "" == value ) { 
    // is empty string 
} 

In the past when fetching values from the db or deserializing objects from another node, this test failed, because the two string instances were indeed different object references, albeit they contained the same data.

So the fix for those situations was

if( "".equals( value ) ) {
   // which returns true for all the empty strings
}

I'm fine with that. That's clearly understood.

Today this happened once again, but it puzzled me because this time the application is a very small standalone application that doesn't use network at all, so no new string is fetched from the database nor deserizalized from another node.

So the question is:


Under which OTHER circumstances:

"" == value // yields false 

and

"".equals( value ) // yields true

For a local standalone application?

I'm pretty sure new String() is not being used in the code.

And the only way a string reference could be "" is because it is being assigned "" directly in the code (or that's what I thought) like in:

String a = "";
String b = a;

assert "" == b ; // this is true 

Somehow (after reading the code more I have a clue) two different empty string object references were created, I would like to know how

More in the line of jjnguys answer:

Byte!

EDIT: Conclusion

I've found the reason.

After jjnguy suggestion I was able to look with different eyes to the code.

The guilty method: StringBuilder.toString()

A new String object is allocated and initialized to contain the character sequence currently represented by this object.

Doh!...

    StringBuilder b = new StringBuilder("h");
    b.deleteCharAt( 0 );
    System.out.println( "" == b.toString() ); // prints false

Mystery solved.

The code uses StringBuilder to deal with an ever growing string. It turns out that at some point somebody did:

 public void someAction( String string ) { 
      if( "" == string ) {
           return;
       }

       deleteBankAccount( string );
 }

and use

 someAction( myBuilder.toString() ); // bug introduced. 

p.s. Have I read too much CodingHorror lately? Or why do I feel the need to add some funny animal pictures here?

Answer

jjnguy picture jjnguy · Jul 10, 2009
String s = "";
String s2 = someUserInputVariale.toLowercase(); // where the user entered in ""

Something like that would cause s == s2 to evaluate to false.

Lots of code sill create new Strings without exposing the call to new String().