EDIT Thanks for the promptly responses. Please see what the real question is. I have make 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 next validation 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 was on 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 an 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 ( that after reading more the code I have a clue) two different empty strings object reference 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
Mistery solved.
The code uses StringBuilder to deal with a 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?