Use
stringVariable == null
To test whether stringVariable is null.
The equals method (and every other method) requires stringVariable to not be null.
Use
stringVariable == null
To test whether stringVariable is null.
The equals method (and every other method) requires stringVariable to not be null.
if stringvariableis already null, it doesn't exist as a String object anymore, so it won't even have a .equals method! So in the event when stringvariable is null, what you are really doing is null.equals(null), at which point you'll get the NullPointerException because null doesn't have a .equals() method.
Videos
Using "abc".equals(...) is a reasonable precaution against a condition you didn't anticipate, but doesn't really solve any problems. Maybe this particular method doesn't care that myString is null (the string comparison returns false, but that's it), but what about elsewhere? Now there's this null value working its way through your logic that's not supposed to be there.
In this particular case, it might not matter, but in another, letting this invalid value pass through part of the logic could lead to an incorrect state later on (e.g. an address with the city missing). Fail early!
If myString should not be null, then write the code so that it can't be. Add contracts to your methods, or at least some in-method argument validation to ensure invalid values are dealt with before the method's logic ever executes. Then be sure your tests cover these cases.
One goal of programming is robust code, ie. code that doesn't die horribly whenever something unexpected crops up.
in case of if ("abc".equals(myString)), the if clause doesn't get executed if the string is null, so throwing an exception isn't necessary. Of course it could be caused by bugs in code, but those should be found during developing/testing, not in production, by the customer!
Actually, i would take "abc".equals(myString) as an indication that the programmer explicitly didn't care whether the string was null or not. In critical code, i'd expect a lot more explicit checking.
To the question of whether this asymmetry is inconsistent, I think not, and I refer you to this ancient Zen kōan:
- Ask any man if he's as good as the next man and each will say yes.
- Ask any man if he's as good as nobody and each will say no.
- Ask nobody if it's as good as any man and you'll never get a reply.
At that moment, the compiler reached enlightenment.
An exception really should be an exceptional situation. A null pointer might not be a programmer error.
You quoted the existing contract. If you decide to go against convention, after all this time, when every Java developer expects equals to return false, you'll be doing something unexpected and unwelcome that will make your class a pariah.
I could't disagree more. I would not rewrite equals to throw an exception all the time. I'd replace any class that did that if I were its client.