Comparing strings in an if: !string.equals("") vs !"".equals(string) [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between these two conditions?
I am doing some code cleanup and NetBeans made a suggestion to change
if(!billAddress1.equals("")) to if (!"".equals(billAddress1)).
What is the difference between the two, and the advantages of using the suggested version over the readability of the original version?

billAddress1.equals("") will cause a NullPointerException if billAddress1 is null, "".equals(billAddress1) wont.

// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))
// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))

!"".equals(billAddress1) will never cause an NPE, so it allows a more compact syntax by allowing to get rid of the billAddress1 == null that would otherwise be required.

The latter will not cause a Null pointer exception if the value is null.

One saves you from NPE as others have pointed out. But if you are sure it's not going to be null then the better way to check if a string is empty is to use the String.isEmpty() method, that's what the code seems to be trying to do.

The first one has a potential to cause NullPointerException.

Related

"you shouldn't catch NPEs" - is this context based? [duplicate]

This question already has answers here:
When is it OK to catch NullPointerException?
(10 answers)
Closed 3 years ago.
Bear with me, as I've read a bit on this and I'm still not sure if I'm thinking about this correctly, but I want to understand this fully...
I've recently found myself in a debate that surrounds a pragmatic approach to code, whereby the feedback I've been given is (I think) a misrepresentation of general Software Engineering advice.
So consider you have a method that handles an input - let's say you take in a String and format in a particular way (assume it's not a way that any existing Java until provides). The method could throw a NPE if null is passed in, because that shouldn't happen.
I didn't add in any NPE handling like the Apache Commons library for StringUtils has, where when you pass in null it provides back an empty string because, in the context of the method, a null shouldn't be provided. I wanted to leave it up to the implementation to determine how to handle this.
The logic for this, by me, is that you wouldn't necessarily want this null value to just be swallowed as normal, but might want to catch this and rethrow the occurance as another exception to explain "this shouldn't have happened" - say, if it was for a step that was considered mandatory.
A colleagues said that "catching NPEs is considered bad practice", but further research on this suggests this is only the case where you're ignoring the NPE (or swallowing it).
To my mind, that's what
if(var = null) { return ""; }
(for example) is doing, whilst actually handling the null as an exception...
try {
myStringMethod( somevar );
}
catch ( final NullPointerException e )
{
Throw new MySpecificException( e );
}
... Is an effective way of handling a mandatory value that shouldn't be null.
In the way it was put across, it seems to suggest a NPE should never be seen - which I agree with, but surely "dealing with it" by somewhat ignoring the cause is actually the wrong way?
NullPointerException is (almost) always a bug. Either a method accept null as an argument, in which case it should never throw NPE. Or it doesn't accept null, in which case the caller is responsible for not passing it.
Catching NullPointerException is (almost) never the solution.

Difference between using variable first and using variable at the end when comparing object? [duplicate]

This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 6 years ago.
I have seen in many places that the constant value is used first and then the variable for example ("ram").equals(a) and in many places I have seen that the variable is used first and then the constant value with which they want to compare for example a.equals("ram").
what is the difference between a.equals("ram") and ("ram").equals(a) ?
which one is better to use and why ?
The first style is safer in situations when variable a is allowed to be null, because you can skip null checking.
When you write
if (a.equals("ram")) { ... }
you must ensure that a is not null to avoid a null pointer exception. This is not necessary for
if ("ram".equals(a)) { ... }
because equals() method is required to process null arguments without throwing an exception:
For any non-null reference value x, x.equals(null) should return false.
("ram").equals(a) is better. The code will never break even if a is null.
saves us from null pointer exception.

why use null != anything instead of anything!=null? [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 7 years ago.
I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null. This is true for below thing too
"true".equals(x).
Why is this so?
anything != null is exactly equivalent to null != anything.
On the other hand, "true".equals(x) avoids the need to check if x is null when doing x.equals("true").
The reason for including constants on the left hand side of an equals expression is to avoid NullPointerException even when the variable is null. This also improves the readability of the expression.
That being said, null!=something is a personal choice and I would prefer using something!=null.
These are two separate practices.
Using null on the left side when comparing to null ensures that you won't, by mistake, use = instead of ==. However, this is a practice taken from languages other than Java, as in Java the expression
if ( something = null )
is going to fail as it does not resolve to a boolean value. In other languages it may be permissible to use a condition whose value is actually a pointer.
Thus this practice has no meaning in Java.
The second practice, as you were told, has to do with preventing a NullPointerException. It should be noted that this practice is controversial, because it allows a null to propagate to a later point in the program, and that usually means that it will be harder to find when it causes a bug.
This is called a Yoda condition. Among other things, it helps prevent an accidental assignment due to a missing = or !, as in foo = null. The reverse, null = foo, would not even compile.
That said, it is purely a stylistic preference. foo != null is logically equivalent to null != foo.
That check is so the program ensures the variable in question has been initialized before reading it. If a program tries to access a null variable, it will crash (specifically in Java it will throw a NullPointerException). It is a critical aspect of defensive programming.
As far as ordering, the evaluation of whether something is null or not is commutative. Meaning:
something != null
Is the same as
null != something
It is all a matter of personal preference. And as #manouti explains above, "true".equals(x) avoids the need to check if x is null when doing x.equals("true"), so you save a line of code.
Seems that some people prefer null != anything, because anything might be quite long expression, so writing null first makes it visible in the narrow window and simplifies code reading ("ok, we just check if something is not null"). But it's totally a matter of style.
As for "true".equals(x), it's well explained by #manouti.

Possible Interview Java .equals [duplicate]

I was asked this question in interview. Which of the following is better to use
MyInput.equals("Something");
Or
"Something".equals(MyInput);
Thanks
I would go for
"Something".equals(MyInput);
in this case if MyInput is null then it won't throw NullPointerException
Here we are sure that the object on which equals() is going to invoke is NOT NULL.
And if you expect NullPointerException from your code to take some decision or throw/wrap it, then go for first.
There is no performance impact
To be the contrarian.... :)
The first line might crash if MyInput is null, but that is just a code-convenience programmers (usually with a C hangover) use when they don't want to assert that 'MyInput' can be null.
If the second option is used, then maybe this line won't cause a NullPointerException, but the following lines might.
I believe that it is better know the possible state of your variables rather than rely on some code-construct that eases your conscience.
Well how about we write our whole code upside down for a change?
Those who like their constants first, how would they feel when they see this?
if ( 2 == i)
Hiding a NullPointerException, in my opinion, is never a benefit but a shortcoming in the design.
If you never expect a NullPointerException but got one, then you need to let your application blow, follow the logs and see why this happened. It could be a business case that you missed altogether :)
If you optionally expect a null parameter and are not interested in handling it separately, then use a utility method like StringUtils.equals(...)
That said, I never allow any of my team members to use the second form because it is not consistent and not readable.
The former will raise a NullPointerException if MyInput is null, while the latter will just return false, so the latter may be preferable in certain cases (or possibly the former, if you don't expect MyInput to be null and want to fail fast).
If you want to be a real smarty-pants you could point out the possibility that MyInput could be a special subclass of String that has over-ridden the equals and hashcode methods. In that case the ordering of the statement is vitally important.
Here's a real-life example - how about if you want to compare Strings that have numbers in them and you want leading zeroes ignored? For example, Lecture1 would equal Lecture01.
i would go to "something".equals(myInput); because variable can be null simply it throw a exception if variable is null .
A good developer will always try to avoid a NullPointerException, hence the best answer would be to use "Something".equals(myInput).

Interview : Java Equals

I was asked this question in interview. Which of the following is better to use
MyInput.equals("Something");
Or
"Something".equals(MyInput);
Thanks
I would go for
"Something".equals(MyInput);
in this case if MyInput is null then it won't throw NullPointerException
Here we are sure that the object on which equals() is going to invoke is NOT NULL.
And if you expect NullPointerException from your code to take some decision or throw/wrap it, then go for first.
There is no performance impact
To be the contrarian.... :)
The first line might crash if MyInput is null, but that is just a code-convenience programmers (usually with a C hangover) use when they don't want to assert that 'MyInput' can be null.
If the second option is used, then maybe this line won't cause a NullPointerException, but the following lines might.
I believe that it is better know the possible state of your variables rather than rely on some code-construct that eases your conscience.
Well how about we write our whole code upside down for a change?
Those who like their constants first, how would they feel when they see this?
if ( 2 == i)
Hiding a NullPointerException, in my opinion, is never a benefit but a shortcoming in the design.
If you never expect a NullPointerException but got one, then you need to let your application blow, follow the logs and see why this happened. It could be a business case that you missed altogether :)
If you optionally expect a null parameter and are not interested in handling it separately, then use a utility method like StringUtils.equals(...)
That said, I never allow any of my team members to use the second form because it is not consistent and not readable.
The former will raise a NullPointerException if MyInput is null, while the latter will just return false, so the latter may be preferable in certain cases (or possibly the former, if you don't expect MyInput to be null and want to fail fast).
If you want to be a real smarty-pants you could point out the possibility that MyInput could be a special subclass of String that has over-ridden the equals and hashcode methods. In that case the ordering of the statement is vitally important.
Here's a real-life example - how about if you want to compare Strings that have numbers in them and you want leading zeroes ignored? For example, Lecture1 would equal Lecture01.
i would go to "something".equals(myInput); because variable can be null simply it throw a exception if variable is null .
A good developer will always try to avoid a NullPointerException, hence the best answer would be to use "Something".equals(myInput).

Categories

Resources