/*line 1.*/
if((name!=null || address!=null)||(!(name.equals("")||address.equals("")))){
sessionNameModel.setObject(""+name);
sessionAddressModel.setObject(""+address);
add(sessionName);
add(sessionAddress);
}
else{
sessionNameModel.setObject("");
sessionAddressModel.setObject("");
add(sessionName);
add(sessionAddress);
}
I am getting null pointer exception in line 1. I know the value of name and address field is null but i have to check in cases when session updates the value. i need to know how to check these variables name and address as null or not..
Assuming that your condition is correct, change:
if((name!=null || address!=null)||(!(name.equals("")||address.equals("")))){
to:
if((name!=null || address!=null)||(!("".equals(name)||"".equals(address)))){
Explanation:
by using "".equals(name) you guarantee that even if name is null (which is possible since you're using || in the previous expression) the comparison will return false instead of NPE. Same goes for address.
if((name!=null || address!=null)||(!(name.equals("")||address.equals(""))))
Here if name==null still you are checking for name.equals which may cause nullpointer same thing happens for address.Instead use && for checking equals only if it's not null.Or you can use "".equals as suggested by alfasin
if((name!=null && !name.equals(""))||((address!=null && !address.equals(""))))
Apart from the discussion,
I think here use of || not needed instead use && as here || can add null in your session which is not proper.
if((name!=null && !name.equals(""))&&((address!=null && !address.equals(""))))
You can try like this
if((name !=null || name.length()==0) && (address!=null || address.length()==0)){
}
else{
}
name = null;
address = null;
if((name!=null || address!=null)||(!(name.equals("")||address.equals(""))))
Analysis;
first checks name!=null, it's false
then checks address!=null, which is false either
then it tries to check if name.equals(""), but since name is null, it will crash because there is no object as name and so no method as equals
as looking at the other lines you have to change the line as
if((name!=null && address!=null)&&(!(name.equals("")||address.equals(""))))
Let's analyse the new line;
first checks name!=null, which is false
since all other conditions are combined with AND and since one of them is false, no need to check anything else, so executes the second line
At first cobait is right:
if((name!=null || address!=null)||(!(name.equals("")||address.equals(""))))
If either the variable name or the variable address is null, the following code will still be executed. This is probably causing your nullpointer.
Better expression would be if((name != null) && (address != null)) ....
If you want to execute the code for at least for one of the variables, if it is not null, you should split your if statements.
Another alternative for your check would be using the apache commons library and call the function isBlank(). This function checks both, if the String is not null and if it's not emtpy.
Related
I wrote this code, which passes all the test cases
//passes 1100/1100 cases
while (slow != null && slow.next != null && fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next
}
On the other hand, this code does not, but seems to be very similar.
//passes 1/1100 cases
while (slow != null && slow.next != null && fast.next != null && fast != null) {
fast = fast.next.next;
slow = slow.next
}
I just noticed that just by changing the order of condition statements in while(), the number of test cases that pass changes. Why is it so?
Java if-statements use something called short-circuit evaluation, where if there is an && where the first condition is false, or an || where the first condition is true, then it will not evaluate the rest of the condition, because it already knows what the result will be. If there is an && and the first statement is false, then it doesn't matter what the rest of the statements evaluate to, since the whole thing is false, and vice-versa if there is an || and the first statement is true.
A second issue is that if an object is null, then calling any method or accessing any property of the function will throw a NullPointerException. This can be avoided by checking if an object is null before using it in cases where you know it might be null. In your linked list, evidently you are concerned that a node might be null, so you check before accessing its next.
These two combine together in your example. If you do
if (item != null && item.property != null) {}
and item is actually null, then because of short-circuit evaluation, Java will never actually check item.property to see if it's null as well, because it already knows the combined statement will be false.
Conversely, if you do
if (item.property != null && item != null) {}
then Java will try to access item.property, which will throw a NullPointerException if item is null.
In your case, evidently many of your test cases had situations where fast was null at some point. The example where they passed would have avoided calling fast.next when fast is null because of short-circuit evaluation, whereas the second example never avoids the NullPointerExceptions at all.
I have a code snippet as below. Here there is a nested if else loop as well as multiple conditions [all different parameters]. What is the best way to optimize this.
if(request!=null && !StringUtils.isBlank(request)) {
if(request.getFirstName()!=null && !StringUtils.isBlank(request.getFirstName())
&& request.getLastName()!=null && !StringUtils.isBlank(request.getLastName())
&& request.getAge()!=null && !StringUtils.isBlank(request.getAge())
&& request.getAddress()!=null && !StringUtils.isBlank(request.getAddress())
&& request.getPhoneNumber()!=null && !StringUtils.isBlank(request.getPhoneNumber())) {
return true;
}else {
return false;
}
}else {
return false;
}
I had thought of using switch case and for loop as well but all the conditions are based on different variables, I didn't see it as compatible.
StringUtils from commons-lang already has a method which accepts an array of Strings. It will check for null or empty or blank strings. So all your checks boil down to:
return !(request == null || StringUtils.isAnyBlank(
request.getFirstName, request.getLastName,
request.getAge, request.getPhoneNumber));
You can try StringUtils.isAnyBlank(). Please refer attached link.
isAnyBlank : https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isAnyBlank-java.lang.CharSequence
If you don't use commons-lang dependency you can simply use Stream API (Java 8+)
Boolean allNonBlank = Stream.of(
request.getFirstName(),
request.getLastName(),
request.getAge(),
request.getPhoneNumber())
.allMatch(it -> it != null && !String.isBlank(it));
You have a few syntax errors
You are passing request to StringUtils but it doesn't appear to implement CharSequence
You are using !! instead of !
You invocation of the get methods does not include the () to mark it as methods.
Although not an error, you do not need nested if-statements here. Using unnecessary if-else-blocks can make it harder to decipher what the code is doing. It can, however, allow for comments to describe why certain conditions are being checked or whatever. None of that seems relevant here. In fact, you can pass the result of the boolean operation without any if-statement. Using if-statements that return true or false looks like this.
if (<condition-is-true?>) return true
else return false;
Which can be simplified to...
return <condition-is-true?>;
Further, assuming you are using using Apache StringUtils, you do not need to check for null first - the isEmpty(CharSequence) method does that. Additionally, StringUtils includes the isAnyEmpty(CharSequence...) method so you can pass all of the Strings at once.
return request != null && !StringUtils.isAnyEmpty(
request.getFirstName(),
request.getLastName(),
request.getAge(),
request.getAddress(),
request.getPhoneNumber());
Is it possible to do something like this?
dog.setIsBarkingIndicator(mailman.getIsAtDoor() != null && mailman.getIsAtDoor().equals("N") ? false : true);
But for what I researched, this is basically the same as: dog.setIsBarkingIndicator(mailman.getIsAtDoor() == null || !mailman.getIsAtDoor().equals("N"))
So it actually sets it at false if its null or not equals to "N"? Did I understand correctly?
Is there any way to check the null without using the if condition?
Thank you!
So, your logical condition is basically like the following:
mailman.getIsAtDoor() == null || !mailman.getIsAtDoor().equals("N")
You can change the instance which performs equal operation. The one instance here is a constant string literal - that means it is never a null value, so it can always perform an equality operation. The condition you are looking for is here:
!"N".equals(mailman.getIsAtDoor()).
This approach does not require from you to check null value of the mailman.getIsAtDoor().
Perhaps the dog or the mailman variable is null. So please try the following code:
if (dog != null && mailman != null)
{
dog.setIsBarkingIndicator(!mailman.getIsAtDoor().equals("N"));
}
I have this code. it is the row exception filter in the right hand map of a tMap:
row2.method.equals("Twitter") && (
row2.last_notified.equals(null) ||
row2.frequency.equals("Everytime") ||
(row2.frequency == "Hourly" && TalendDate.diffDate(TalendDate.addDate(row2.last_notified,1,"HH"), TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")), "HH") > 0) ||
(row2.frequency == "Daily" && TalendDate.diffDate(TalendDate.addDate(row2.last_notified,1,"dd"), TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")), "dd") > 0)
)
I have a nullPointerException. I know that frequency is not null, as is method. I know that last_notified is null. based on my logic, all rows with "Twitter" as a value with no last_notified should pass. However, it looks like I failed with this.
I understood that OR statements go from left to right. If the first value comes back True, then the OR SHOULD return true? What am I missing?
Regarding
row2.last_notified.equals(null)
Don't test for null with the equals method as that risks throwing the NPE exception since you'll be attempting to call a method on a null variable. Always use == instead since you're not testing the notified reference's value but rather whether the reference itself is null.
So do
row2.last_notified == null
Also regarding
row2.frequency == "Daily"
It's the exact opposite here as you're comparing Strings wrong -- use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
Instead do:
row2.frequency.equals("Daily")
Product p = dao.checkProduct(pnumber);
ExpensiveProduct ep = dao.checkexpensiveProduct(pnumber);
if ((p.getNumber() == null)&&(ep.getNumber()==null) ){ // java.lang.NullPointerException
//do something
}else{
//do something
}
Why this statement giving java.lang.NullPointerException
Do I have any other way to check this?
The only non-trivial possibility where this code can throw NPE is pnumber being Integer where checkProduct() or checkexpensiveProduct() expects int (or similar).
Other trivial reasons are dao or p being null (easy to check).
Try it like this:
if ((p != null) && (p.getNumber() == null) && (ep != null) && (ep.getNumber()==null) ){
NullPointerExceptions (NPEs) occur when you call a method or access a property of a null object.
To check for nulls, you could print the values of your variables before you try to use them, or step through your program with a debugger and check what the variables' values are when you reach the line where the exception happens.
EDIT:
Regarding your comment
i need to check p.getNumber() and ep.getNumber() both returning null and get ture on that statement
your existing code
if ((p.getNumber() == null)&&(ep.getNumber()==null) )
is already doing that. Since you're getting an NPE on that line, p itself is null, or ep is null, or both. You should examine your checkProduct() and checkexpensiveProduct() methods, where p and ep are set, to see if they're working correctly.
check your p variable and ep variable .One of them is null.check
why
dao.checkProduct(pnumber)
or
dao.checkexpensiveProduct(pnumber); is returning null
What line is giving the NullPointerException? Be sure that p or ep are not null.