Posted November 9, 2022 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
Posted November 10, 2022 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
Posted November 15, 2022 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
Posted November 17, 2022 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