Please pay attention to your comparison of the string Object. You compare the reference of the string literal with the reference of your argument object. that cannot be equal... To identify, if two strings are equal, use the equal() ore equalIgnoreCase() methods.
what nicholas and stefan has said is correct. "==" operator always compares the references (addresses) but not the contents pointed by the addresses. So for string comparisions it's advisable to use equals() or equalIgnoreCase() functions.
keep in mind that while comparing a string object aganist a string constant always proceed as follows:
Originally posted by Ravi Kishore: a new dummy object is created for the string constant "beans" and then the comparision takes place. which will consume memory unnecessarly.
It shouldn't matter. The "beans" is a string literal; as such, an object is always created. At runtime, there's no difference between a "string object" and a "string literal;" both are instances of java.lang.String. (OK, the string literal is stored in the literal pool...)
The primary reason for placing the string literal first is to avoid NullPointerExceptions.:
could throw a NPE if food were null.
returns false if food were null.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
By taking about the handling of NullPointerException for null strings, currently, we try to use an alternative approach.
We used the APIs provided by Jakarta Common, the StringUtils. This package provides lots of functions for string manipulations, like isEmpty(), isBlank(), equals(), etc. And the APIs have been internally handled the null cases, i.e., if x is null, StringUtils.isEmpty(x) returns true instead of throwing the NullPointerException.