I have the following snippet of code that is causing me bother, where currentRate and secondCurrentRate are Double objects, correctly defined:
(currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
This should check each each Double for null-ness and assign the value null accordingly. However, if secondCurrentRate is null, this causes a NullPointerException.
I have changed the snippet to this:
(currentRate == null | secondCurrentRate == null) ? null : currentRate * secondCurrentRate;
And this works as expected. My question is why is this happening? I could understand it if I was calling some method on the objects but my understanding was that NullPointerExceptions were thrown when a method was called on a null object. There is a null object but there is no method call.
Can anyone offer any insight into this? This is running in Java 5.
I think your problem is elsewhere.
This works :
Double currentRate=null, secondCurrentRate =null;
Double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
But if you've done this, it will cause a NPE:
Double currentRate=null, secondCurrentRate =null;
double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
The type of the conditional operator is actually quite complicated. I believe what happens in your first example, is this: The second operand of the conditional,
currentRate * secondCurrentRate
is of type double, and this also becomes the type of the entire expression. Then, when either of the values are null, it tries to set the value of the expression to the Double null, which is unboxed into a double and causes a NPE.
The reason the second expression works is due to slightly different semantics of the conditional expression in this case.
Related
Please find my below code that am checking for null using ternary operator before am setting the value to my bean class attributes.
doc.setCatalog_description(sourceAsMap != null && sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
Is there anyother way to simplify this code like below., Am just exploring by using org.apache.commons.lang3.ObjectUtils; methods. But am not sure that it is correct or not.
doc.setCatalog_description(ObjectUtils.identityToString(sourceAsMap.get("catalog_description")));
I think you are looking for the method ObjectUtils.toString(Object).
if (sourceAsMap != null) {
final String description = ObjectUtils.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
If you are using jdk7 or higher, you can replace the method by java.util.Objects.toString(Object).
if (sourceAsMap != null) {
final String description = Objects.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
I don't know if sourceAsMap can be null, but if you are setting several parameters, you should check if it is null just once.
In the interest of readability and clarity I would suggest just extracting this bit of functionality into its own method:
String getDescOrNull(Map<String, Object> sourceAsMap) {
final String key = "catalog_description";
if (sourceAsMap == null || !sourceAsMap.containsKey(key)) {
return null;
}
return sourceAsMap.get(key);
}
then:
doc.setCatalog_description(getDescOrNull(sourceAsMap));
am checking for null using ternary operator before am setting the value to my bean class attributes
So I think you need to set multiple bean attributes from the map.
Best and simple solution will be to check null condition on sourceMap for once and then use ternary operator for setting attributes.
if(sourceAsMap != null){
doc.setCatalog_description(sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
doc.setAnother_description(sourceAsMap.get("another_description") != null ? sourceAsMap.get("another_description").toString() : null);
}
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
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.
Can somebody explain me why I am getting a NullPointerException here:
String s = request.getParameter("tbExample");
_tbExample = new Double (Double.valueOf(s).doubleValue());
s may be null. According to javadoc, if s is null, valueOf will throw a null pointer exception.
Try checking s for null before continuing.
Probably the tbExample parameter does not exist in your request.
Therefore null is being returned to indicate that fact, and is being assigned to s. This is then passed to Double.valueOf, which is invalid input.
Try something like this:
String s = request.getParameter("tbExample");
if(s == null)
{
// Handle the error.
// You could log something, throw exception, exit early, etc.
// Do whatever is appropriate for your application.
}
else
{
_tbExample = new Double (Double.valueOf(s).doubleValue());
}
I can see why you are confused here. You are taking a String, parsing it into a Double, turning it into a double and back into a Double again. A much simpler solution is to do
_tbExample = s == null ? null : Double.valueOf(s);
This handles the situation where s is null and turns a String into a Double
Here is a simple test program for you.
Double _tbExample;
String s = null;
_tbExample = s == null ? null : Double.valueOf(s);
System.out.println("_tbExample="+_tbExample);
prints
_tbExample=null
1) if(null != parentObj.childObj)
2) if(parentObj.childObj != null)
Do you think that "1" will avoid a potential null pointer exception in the case where 'parentObj' is null, in contrast to "2"?
No.
If parentObj is null then any attempt to call a method or reference a field will result in a NullPointerExcepton. != always evaluates both sides.
Just check if parentObj is null first and handle it appropriately.
Why not just if(parentObj != null && parentObj.childObj != null) ?
If parentObj is null, referencing any method/field on parentObj will result in an NPE. In other words, you need if (parentObj != null && parentObj.childObj != null) to avoid an NPE. Groovy cuts down on this (very common) type of verbosity with the safe navigation operator, which lets you write if (parentObj?.childObj).