An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the the array elements are null or refer to the empty String. Set the variable hasEmpty to true if any elements are null or empty-- otherwise set it to false.
hasEmpty=false;
for (int i=0;i<names.length;i++)
if (names[i].trim().equals("") || names[i]==null)
hasEmpty=true;
Whats wrong with my code?
Calling trim() first will result in a NullPointerException should a member of the array be null. Reverse the order of the conditions - the short-circuiting nature of || will then ensure that trim is only called on a real String object.
Consider names[i].trim().
When names[i] is a String, you really have something like someString.trim() which works fine.
When names[i] is a null, however, you really have something like null.trim(). You've already discovered that null doesn't allow a trim() method. (In fact, I'm not even really sure what 'null' is.)
Therefore, you must check for null before you invoke trim().
When you have a && b, where a and b are expressions, the checks are made left-to-right and the parser stops as soon as the issue is settled. So for the logical and operator (&&), if a is false then b is never checked. This is what allows
if (a != null && a.trim().length() > 0) { ... }
to work. if a is null, the a.trim() part is not executed since it would be pointless from a logical point of view; the value of the conditional has been decided.
Similarly for
if (a == null || a.trim().length() == 0) { ... }
if a is null then the a.trim() part is never performed and we don't get an error.
You can use the Apache Commons Lang's isBlank() to check a String:
if (StringUtils.isBlank(names[i]) {
...
}
StringUtils.isBlank is checking if the String is null or empty (i.e. if it is equals to "" when all blank characters are removed).
It's throwing a Null Pointer Exception because you're trying to run a method on a null object:
if (names[i].trim().equals("") || names[i]==null)
So, anytime that names[] has ONE name that's null, it will throw the exception. One way to solve the problem is to switch the boolean statements in this if statement:
if (names[i]==null || names[i].trim().equals(""))
Related
This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed last month.
I have some code that does the following:
if(object == null || object.value.equals(" ")) {
// do something
}
else {
// do something else
}
The above seems dangerous to me because if I switched the order of the two conditions or changed this to an AND expression, the code will crash when object is null, but I also read somewhere that Java guarantees operands are evaluated from left to right. That said, I also read do not assume this to be true.
I am confused by all this conflicting advice and wondering whether the above code constitutes a bug. That said, what is the best way to recode this if indeed this is considered bad practice?
In Java && and || are short circuit (boolean!) operators. So everything works as assumed. No unnecessary evaluation running into an error. Some languages Name these and-then, or-else.
boolean newGraphRequired = graphNode == null
|| gaphNode.timeStamp() != moduleNode.timeStamp();
Conditions become more straightforward.
Use below piece of code -
if(object == null || (object != null && " ".equals(object.value))) {
// do something
}
else {
// do something else
}
Also Always keep constant values in left side of equals, it will prevent NPE.
For Above code if object is null or object.value is " "(space), it will go inside if otherwise it will go in else.
So I've done a some readings on NullPointerExceptions in Java but I'm still not really understanding it completely.
why does this work?
if ((department != null && department.equals("COMP")) || (department != null && department.equals("COMM")))
{
this.department = department;
}
and also another method that worked was when I first checked for != null and then did a second nested if statement to then check for "COMP" or "COMM".
compared to the above, how come this one doesn't work?
if (department != null || department.equals("COMP")) || department.equals("COMM")))
{
this.department = department;
}
Like most, I don't like having found a solution by accident but not really understanding why it's a solution. I'm still very new to programming so I'm trying to understand what's actually happening underneath the hood. I understand things the easiest when given a metaphor to compare with, it'd really help if someone can explain it for me that way ><;;
Thank you guys very much!
The answer to your question is in the boolean algebra and how you are implementing the conditions
Doing this
((department != null && department.equals("COMP")) || (department != null && department.equals("COMM")))
is equivalent to doing
A&B | A&C that can be resumed to A&(B|C).... so A must be met AND either B OR C in order to execute the code...
so far so good.
the second condition
if (department != null || department.equals("COMP")) || department.equals("COMM")))
is equivalent to doing
A | B | C that can NOT be resumed/simplified to anything
.... so A must be met OR either B OR C in order to execute the code...
if A is null first condition fails, then java tries to check condition B but since B is null it explodes with a nice NullPointer Exception
Because of boolean logic and because of runtime optimization.
In a boolean sentence if all operands are AND and one sentence is False all the sentence is False. So when runtime evaluate the first sentence and discover that is false it doesn't evaluate the others AND sentence. Than for AND case, no NullPointerExceptions exception, that means try to access an object that is null, may happen if you check it first. Otherwise if the sentence contains Only OR operand, runtime have to evaluate all the sentence, so the Null pointer exception happens because the object is null, the first sentence in OR is safe because you can compare a null object to NULL, but the second is not, because you cannot access a null object property.
Fixing sonar violations and got a warning " Equals Avoid Null:
String literal expressions should be on the left side of an equals comparison." for:
if (title != null && !title.equals("")) {
//rest of loop
}
I changed it to:
if(!("").equals(title) && title != null){
//rest of loop
}
Is that change okay? Will it fix the violation? Could somebody possibly explain to me why the original is a violation? I don't understand the issue and have read:
https://sonar43.spring.io/rules/show/checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck?layout=false
amongst one or two other articles, but I stil don't see what the problem is...
The warning is telling you that it's not sure that title won't be null. A literal, however, such as your empty string, can never be null by definition. And since equals can handle null as an argument you're avoiding a potential NullPointerException by writing <literal>.equals(<somebject>). If you're not using title within the if statement there's no need for further null-checking:
if(!"".equals(title)){
//rest of loop
}
However, since you're checking if something doesn't equal a literal it makes little sense to let null values pass through.
The docs also has this related note:
Also, it is pretty common to see null check right before equals
comparisons which is not necessary [...]
Which one is recommended and to be used to check the Object null-ness?
null != Object
or
Object != null
and other way
null == Object
or
Object == null
...and is there any difference between them?
(In)equality is commutative, so there is no difference.
Historically the former stems from C to avoid accidentally assigning a value in a conditional statement, however that mostly applies to ==, not !=. Also Java requires the condition in a conditional statement to have a boolean value, so the only place where it could go wrong nowadays would be
if (a == false) ...
if you accidentally omit one of the =. A rare case, I guess (though probably not so much, given what students frequently write in their first two terms). Joonas also points out another (more obscure) case in the comments.
It's always more readable to use
Object != null
because that reads as "the object is not null", which is literally what the condition is.
The only case where you want to swap the two is to avoid accidentally using
Object = null
which will return true even though it is not the desired behavior, when you wanted to say
Object == null
but in reality not only do modern tools catch these kinds of mistakes, but wide use of the reverse can actually be an impediment to anyone who has to read the code.
I have a setter method.
Then when another (say generate) method is run, I need to check the value of my fields.
So in the case of String property, I need to know if it contains the value or if it was not set.
So it may be null, "" or something meaningful, there are 3 possibilities.
And it is rather boring to check first for a null value :
if (s != null)
then for an empty String
if (!s.isEmpty())
is there a one-step check here? You can tell me that I can initialize my String field with an empty String. [ IS IT COMMON? ] But what if someone passes a null value to the setter method setS?
so do we always have to check if the Object value is null or not before doing something with that object?
Well, yes a setter method can check it's values and also a getter method can return a non-null value if the field is null. But is it the only solution? It 's too much work in getters & setters for a programmer to do!
Commons library, StringUtils.isBlank() or StringUtils.isEmtpy().
isEmpty is equivalent to
s == null || s.length() == 0
isBlank is equivalent to
s == null || s.trim().length() == 0
if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}
In the jakarta commons there is a StringUtils.isEmpty(String).
use org.apache.commons.lang.StringUtils, the method StringUtils.isNotBlank check both nullity and emptiness.
Add maven dependency for com.google.guava
Then in your code:
import com.google.common.base.Strings;
if(!Strings.isNullOrEmpty(s)) {
// Do stuff here
}
If you are doing android development, you can use:
TextUtils.isEmpty (CharSequence str)
Added in API level 1
Returns true if the string is null or 0-length.