You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.
It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).
You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.
It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).
Use Objects.equals() to compare strings, or any other objects if you're using JDK 7 or later. It will handle nulls without throwing exceptions. See more here: how-do-i-compare-strings-in-java
And if you're not running JDK 7 or later you can copy the equals method from Objects like this:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
Java comparison == is not null-safe?
Best Way to Check if a String is Null or Empty in Java - TestMu AI Community
java - Is "use "abc".equals(myString) instead of ...
java - Compare Strings avoiding NullPointerException - Stack Overflow
Videos
When I type
string1 == string2
IntelliJ tells me to switch to equals(), which it says is null-safe.
But is == operator not null-safe?
I tried null == "abc", "abc" == null, null == null, but they consistently gave me right false false true.
What am I missing here?
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.