-
November 9th, 2022, 09:10 AM
#1
Java equals() selection
In Java, if I try to do.equals() on a null string, a null pointer error is issued. I’m wondering whether I can perform the following if I’m attempting to compare if a string is equal to a constant string:
Code:
MY CONSTANT STRING.equals(aStringVariable)
I’m sure it’ll work, but is this simply extremely bad code?
This is a common Java idiom known colloquially as a Yoda condition. Personally, I prefer to handle the null situation directly, but the Yoda method is widely used, and any competent Java programmer should quickly grasp what is going on. How should I proceed?
-
November 9th, 2022, 05:25 PM
#2
Re: Java equals() selection
Originally Posted by Nathan D
How should I proceed?
If the null pointer has meaning and represents "nothing" or "empty" or something of that kind, I would use the Yoda condition. Otherwise, the null pointer is an error, and I would check for it directly.
Tony Hoare, the inventor of the null pointer, calls it his billion-dollar mistake. The best strategy is to avoid them. You may search the internet for suggestions.
-
January 6th, 2023, 11:57 AM
#3
Re: Java equals() selection
Originally Posted by Nathan D
In Java, if I try to do.equals() on a null string, a null pointer error is issued.
Sorry for late answer but I regained the login on this forum only today.
Yes, you get a NullPointerException. And if you want to avoid this, there are some possibilities:
1) The classic null-safe explicit test:
if (yourStr != null && yourStr.equals("expected"))
2) The static equals() in java.util.Objects (JDK 7+) which is null-safe:
if (Objects.equals(yourStr, "expected"))
3) There is a similar static utility in notable libraries like Google Guava
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|