Error while attempting null check - java

I am checking for null before doing a certain operation but I have run into some issues. Following is the code:
if (c != null && c.size() != null) {
if (c.size() > 0) {
return (Application) c.toArray()[0];
}
I am getting a 'The operator != is undefined for the argument type(s)int, null' at the point
c.size() != null. I understand the return type for the size method is an integer, is that why I am getting this error? Hope someone can advise. Thank you.

int is a primitive type and is not an Object so is not a reference that can be null. Read more in this previous answer
Then in your code just remove that condition.
And also is preferred you use c.isEmpty() rather than c.size()>0
Your code would look like this:
if (c != null && !c.isEmpty()) {
return (Application) c.toArray()[0];
}

First of all, the result of c.size() is an integer. An int is a primitive, and it cannot be null. Only objects can be null.
Second, c.size() will never return null, so the check
c.size() != null
is unnecessary.
Note: There are wrapper classes for each primitive type. For example
Integer i = 4;
i = null; // valid
That assignment will be valid because i is an instance of the class Integer.

Related

Why null check is necessary in the below code?

public boolean isValidCardDetails(CardDetailsTypeBean cardDetailsTypeBean) throws EnrollmentReqInvalidException {
if (cardDetailsTypeBean.getCardNumber() == null || "".equals(cardDetailsTypeBean.getCardNumber())) {
throw new EnrollmentReqInvalidException("ECDOO16", "card no is mandatory");
}
if (cardDetailsTypeBean.getNameOnCard() == null || "".equals(cardDetailsTypeBean.getNameOnCard())) {
throw new EnrollmentReqInvalidException("ECDOO17", "name on card is mandatory");
}
if (cardDetailsTypeBean.getCvv() == 0 || "".equals(String.valueOf(cardDetailsTypeBean.getCvv()))) {
throw new EnrollmentReqInvalidException("ECDOO18", "cvv is mandatory");
}
if (cardDetailsTypeBean.getExpDate() == null || "".equals(cardDetailsTypeBean.getExpDate())) {
throw new EnrollmentReqInvalidException("ECDOO19", "exp date must be required");
}
return false;
}
Well here i want to ask after getting card number and checking null,why we use "".equals there..?? can anyone explain me this? little confused?
This line of code:
cardDetailsTypeBean.getCardNumber() == null || "".equals(cardDetailsTypeBean.getCardNumber())
simply verifies if cardNumber is null or if is equal to the empty string. Empty string is different from null value, so this code checks if every field read by a getter returns a non-empty, non-null value.
It's superfluous, actually.
The reason for this is that the order of the equals statement on the other side of the logical comparison is guaranteed not to produce a NullPointerException, since String.equals(null) is engineered to produce false.
The reason it likely exists the way it does is that it's being made explicit that the code is checking for null and an empty string.
"" isn't the same as null because "" is a String value. Your card number might instantiated with ""
null means the reference of card number has no value.

Java boolean precedence comparation with ternary operator

I'd found a nice situation that I don't understand at all related to Java boolean operator precedence. I know and verify with the oracle official documentation here that && and || have precedence against ternary operator ? :
Now I have a weird line in my code similar to that
if (a.getItem() != null && a.getItem().getOtherItem() != null?true:a.getItem().getOtherItem().getSomevalue())
{
......
}
What I get, well, a nice java.lang.NullPointerException at a.getItem().getOtherItem() becouse a.getItem() is null. How I can solve it, encapsulate it between parenthesis
if (a.getItem() != null && (a.getItem().getOtherItem() != null?true:a.getItem().getOtherItem().getSomevalue()))
{
......
}
So my question is why I get a NullPointerException if I follow the Oficial Documentation previously linked && has precedence against ?: and && is short circuit evaluated (answered also here in some questions).
It seems you are confused about what “higher precedence” means. Let’s explain with a simple example:
The operator * has higher precedence than the operator '+'. This means that the expression a*b+c is evaluated like (a*b)+c. The same applies to the && operator and the ternary operator:
&& has higher precedence than the operator ? :. This means that the expression a&&b?c:d is evaluated as (a&&b)?c:d.
Hence the operator precedence works as documented in your example. It does exactly what you requested:
if (a.getItem() != null && a.getItem().getOtherItem() != null?
true:a.getItem().getOtherItem().getSomevalue())
If a.getItem() is not null and a.getItem().getOtherItem() is not null evaluate to true, otherwise to a.getItem().getOtherItem().getSomevalue(). So when either of the values is null, the code will attempt to evaluate the third term which will yield to a NullPointerException.
It’s not clear what you actually want to achieve. In your second example you say:
if (a.getItem() != null && (a.getItem().getOtherItem() != null?
true: a.getItem().getOtherItem().getSomevalue()))
so you want to interpret the case when a.getItem() is null as false but in the braced term you request to interpret the case when a.getItem().getOtherItem() is not null as true while the case that a.getItem().getOtherItem() is null should cause getSomevalue() to be called on the reference that you just have proven to be null.
What you most likely want to do is to evaluate a.getItem().getOtherItem().getSomevalue() if the all values are not null:
if (a.getItem() != null && a.getItem().getOtherItem() != null?
a.getItem().getOtherItem().getSomevalue(): false)
Note that you can express the same without the ternary operator at all. The equivalent statement would be:
if (a.getItem() != null && a.getItem().getOtherItem() != null
&& a.getItem().getOtherItem().getSomevalue())
In the case the fall-back value ought to be true like in
if (a.getItem() != null && a.getItem().getOtherItem() != null?
a.getItem().getOtherItem().getSomevalue(): true)
the same can be expressed as
if (a.getItem() == null || a.getItem().getOtherItem() == null
|| a.getItem().getOtherItem().getSomevalue())
Whenever you see true or false in a compound boolean expression you can be sure that there is something wrong.
The general use case for ? is to replace an if in a simple assignment branch, something like:
int a;
if(isOdd(b) || isPrime(b))
{
a = b;
}
else
{
a = -b;
}
into simply
int a = isOdd(b) || isPrime(b) ? b : -b;
And for this use case, it makes sense that && and || have precedence over ?.
The confusion arises only if ? returns boolean, the way you use it inside an if, which in my experience is very rare.
iI'd say that in your if statement
if (a.getItem() != null && a.getItem().getOtherItem() != null?true:a.getItem().getOtherItem().getSomevalue())
the following most inner part must be evaluated first
null?true:a.getItem().getOtherItem().getSomevalue()
so that the following part can be put together
if (a.getItem() != nulla.getItem().getOtherItem() !=<result_from_most_inner_part>)
In any case this if statement is ugly. Make the code rather readable and the compiler will do its part :P

Is there any chance of this code printing null?

String readwidget(int a, int b){
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget.getText() != null){
Task.sleep(10);
System.out.println(readwidget.getText());
return readwidget.getText();
}
Task.sleep(10);
return GOT_NULL;
}
while(readFirstWidget.equals(GOT_NULL) && t5.isRunning()) {
readFirstWidget = readwidget(1184, 13);
Task.sleep(50,80);
}
This piece of code is crashing with nullpointerexception once in while(1 out of 50 time) and it prints null at that point of time which it should not. Can anyone please help me to find out the causes? Thanks in advance.
You mention in a comment that Widgets.get(a,b) can return null. Given that, you need to guard against that possibility by checking the return value from the method for null prior to actually calling any instance methods on it. You aren't doing that, and so you are crashing in that case.
All you need to do is add the null check and your code should be fine:
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget != null && readwidget.getText() != null) {

using method that take variable number of parameters

I am trying to make a method that build new object of the class (PhoneBook) using different constructors according to the number of parameters ,, but it gives an error
( Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 )
public static PhoneBook createObjects(String fName,String lName,String num,String...optional)
{
n++;
if (optional[0]==null)
ArrayOfObjects[n]=new PhoneBook(fName,lName,num);
else if (optional[1]==null)
ArrayOfObjects[n]=new PhoneBook(fName,lName,num,optional[0]);
return ArrayOfObjects[n];
}
Instead of checking whether optional[0] == null, you should examine optional.length to determine if the optional parameter is present.
The same goes for optional[1].
Rather than checking optional[0] and optional[1] here, you should check to optional.length. Also, keep in mind that optional itself may well be null, so something like:
if(optional != null) {
if(optional.length > 0) {
// I now know that optional has at least one element in it, and optional[0] should be valid, though I don't know that it is non-null.
if(optional.length > 1) {
// I now know that optional[1] is valid, though I do not know it is non-null.
}
}
}
if you NEED non-null:
if(optional.length > 0 && optional[0] != null)
The second part, optional[0] != null will only be called if the first evaluates to true.

Variable can only be null shows eclipse

I have wriiten a method like this
public ArrayList<T> GetDoctorDetail(String name)
{
if (name!=null || !name.isEmpty() || name!="")
{
//Statements
}
}
but in eclipse !name by underline with a yellow line show
Null pointer access: The variable name can only be null at this location.
why? and what is the solution.
If name is non-null, the conditional || operator won't evaluate the second operand at all. So the only case in which the second operand can be evaluated is when name is null, in which case it will throw.
I suspect you want
if (name != null && !name.isEmpty())
{
// Use name
}
Or possibly:
if (name == null || name.isEmpty())
{
// Show an error message
}
Note that comparing strings with == and != is also almost always the wrong thing to do, as it compares references. You would normally use equals instead. Not only that, but it would be useless anyway here - it could only be equal to "" if it's empty, so it's the exact same condition as the second operand.
The first part of the oR condition will only fail if name = null. Hence the second part will throw a null pointer exception.
The correct way to write that condition is
if (name!=null && (!name.isEmpty() || name!=""))
if (name != null && !name.isEmpty()) {
// Now the name variable has valid content
}
Note - The logic is always much easier to understand if you create "positive" checks:
if (name == null || name.isEmpty()) {
// Now name is either null or empty
} else {
// Now the name has valid content
}
Try to avoid conditions that check for "negative" states, like "is not null" and "is not empty". They're nothing but brain twisters ;)

Categories