asha91

Java equals() selection

4 posts in this topic

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:

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?

0

Share this post


Link to post
Share on other sites

I think variable != null && variable.equals(constant) or the yoda condition could be ok. The advantage I can think of for using the direct check for null is that it will still work if you end up deciding to store the constant in a variable later on. What is this for? If it's a personal project, do whatever you want, if it's for a job or class, ask your team or professor what they prefer. 

0

Share this post


Link to post
Share on other sites
On 10/11/2022 at 6:02 AM, Inkspren_K said:

I think variable != null && variable.equals(constant) or the yoda condition could be ok. The advantage I can think of for using the direct check for null is that it will still work if you end up deciding to store the constant in a variable later on. What is this for? If it's a personal project, do whatever you want, if it's for a job or class, ask your team or professor what they prefer. 

Actually, I am using it for some personal projects. Thanks for the clarification, it really helped me in choosing the best alternative.

0

Share this post


Link to post
Share on other sites

You are hiding that a may be == NULL. And that is a bad idea. If it legitimately may be, say so. If not, do not hide the error.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.