This question already has answers here:
Unwanted NullPointerException in ternary operator - Why? [duplicate]
(2 answers)
Nullpointer exception with conditional operator, (ternary operator) but not with if else [duplicate]
(1 answer)
Closed 3 years ago.
To my understanding following code should not throw Null Pointer exception as I am safely using Optional interface.
However, when I ran this code it is throwing NPE.
public class Test {
public static void main(String[] args) {
final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
}
}
Please let me know if I am mistaken somewhere in my code and help me to rectify the same.
The reason you get a NullPointerException, is that the type of the expression false ? 0 : Optional.ofNullable((Integer) null).orElse(null) is int (by JLS Table 15.25-C).
The expression Optional.ofNullable((Integer) null).orElse(null) evaluates to null, and casting a null to an int results in a NullPointerException.
Surely you'll get a NullPointerException, because your right hand side is just a very verboose way of saying null. You're wrapping a null in an Optional thus forcing the orElse which executes to null.
Having null in a statement that resolves to int, as explained by #Hoopje (even if it's assigned to an Integer variable) leads to a NullPointerException.
Just wrapping null in an Optional still gives you a null when unwrapping it again.
I found the work around
final Integer inte = false ? (Integer)0 : Optional.<Integer>ofNullable(null).orElse(null);
or
final Integer inte = false ? (Integer)0 : Optional.ofNullable((Integer)null).orElse(null);
the type returned by the ternary operator is expected to be int (because of the literal 0).
Related
This question already has answers here:
Java conditional operator ?: result type
(5 answers)
Closed 6 years ago.
I'm getting nullpointer exception if I use ternary operator.
Integer val = null;
Object res = val == null ? val : val.intValue();
But not with if else
Integer val = null;
Object res;
if( val == null ) {
res = val;
} else {
res = val.intValue();
}
Can anyone please explain why?
Thanks
Sudar
The behavior you encountered results from the rules of determining the type of the ternary conditional expression.
In your case, the type of the expression
val == null ? val : val.intValue();
is int.
This is specified by JLS 15.25. :
The type of a conditional expression is determined as follows:
If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
Your second operand is Integer and your third operand is int, therefore the type of the expression is int.
Therefore, when val == null, val is un-boxed (i.e. val.intValue() is called for a null value) and a NullPointerException is thrown.
In your if-else expression val is not un-boxed when its value is null (since you assign it to an Object variable, so there's no NullPointerException.
That said, since you are assigning an Integer variable to an Object variable, your conditions in either of the snippets are pointless (since assigning an int to an Object variable simply boxes the int back to Integer).
You can simply assign
Object res = val;
and get the same end result without the exception.
This question already has answers here:
String.equals() argument ordering
(10 answers)
Closed 3 years ago.
In part of the code for check empty string the programmer use equals() like this:
if ("".equals(name)) {
// some logic
}
Why is it executed from a string value directly? What is the difference from this;
if (name.equals("")) {
// some logic
}
Both of them have the same result, but what is the idea behind doing the first one?
The idea behind using;
"".equals(name)
is that "" can never be null, whereas name can be. equals() accepts null as a parameter, but trying to execute a method from a null variable will result in a NullPointerException.
So this is a shorthand way to evade such possible exceptions. Same goes for any such constant object.
e.g.
final Integer CONSTANT_RATE = 123456;
....
if (CONSTANT_RATE.equals(someVariable)) { .. }
rather than doing;
if (someVariable != null && someVariable.equals(CONSTANT_RATE)) { .. }
This question already has answers here:
Why does String.valueOf(null) throw a NullPointerException?
(4 answers)
Closed 5 years ago.
Today I found a bug in legacy code, which led me to a shocking discovery:
String s = null + ""; //results in "null" string
s = String.valueOf(null); // NullPointerException is thrown
Integer i = null;
s = String.valueOf(i); //results in "null" string
First question is: Why such an unexpected behavior happens?
It mean that a convenient code like this:
String age = person.getAge() + "";
is being totally unexpected.
Second question: What is the best (most elegant) way to get a null instead of "null"
String.valueOf(null) calls public static String valueOf(char data[]) due to method overloading resolution rules (char[] is more specific than Object). That method throws NullPointException for a null argument.
String.valueOf(i) calls public static String valueOf(Object obj), which returns the String "null" for a null argument.
To avoid this exception, either don't call s = String.valueOf(null); (you can always assign s = "null"; directly, or cast the null value to some type other than char[] (for example s = String.valueOf((String)null);).
This question already has answers here:
NullPointerException through auto-boxing-behavior of Java ternary operator
(3 answers)
Closed 7 years ago.
I have the following return statement:
public Boolean foo(String booleanString){
return ("true".equals(booleanString) ? true : ("false".equals(booleanString) ? false : null));
}
when booleanString equal not true and not false I get the NullPointerException.
Is it boxing/unboxing issue?
You guessed it right. For a formal explanation, the answer lies in the JLS:
If one of the second and third operands is of primitive type T, and
the type of the other is the result of applying boxing conversion
(§5.1.7) to T, then the type of the conditional expression is T.
So as you have the primitive true and false in both expressions, the type of your condition expression is boolean.
When you get into the second expression, in the second case, the null reference is converted into boolean with null.booleanValue();, causing the NPE, so that the expression is equivalent to:
return Boolean.valueOf(null.booleanValue());
(then the return type of the expression is re-boxed to Boolean, but it's too late as you guessed it).
For example:
return ("true".equals(booleanString) ? Boolean.TRUE : ("false".equals(booleanString) ? Boolean.FALSE : null));
does not cause a NPE since the type of the expression is Boolean. This, however,
return ("true".equals(booleanString) ? true : ("false".equals(booleanString) ? Boolean.FALSE : null));
causes it because again the same rule applies (since the first expression is the primitive boolean type). So it's equivalent to:
return Boolean.valueOf(("true".equals(booleanString) ? true : ("false".equals(booleanString) ? Boolean.FALSE : null).booleanValue());
As you are returning object type Boolean, then java tries to unbox return value null to a boolean primitive type in a logical expression, where foo() has been using. And you get Null Pointer Exception.
Here is a similar case and my explanation: https://stackoverflow.com/a/30055584/784540
This question already has answers here:
Why does String.valueOf(null) throw a NullPointerException?
(4 answers)
Closed 9 years ago.
In java Doc it is written that String.valueOf() will return "null" if argument is null, but in practical it gives null pointer exception for null argument. I want to understand the reason. Tried looking on GREPCODE, could not get it. Please explain
If you have code like this:
System.out.println(String.valueOf((Object) null));
"null" is printed to the console. If you have:
System.out.println(String.valueOf(null));
a NPE is thrown.
That is because valueOf is overloaded.
String.valueOf(Object)
String.valueOf(char[])
To explain the NPE, if you examine the code for String.valueOf(char[]):
return new String(data);
and the constructor for String is:
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
On this line, a NPE is thrown with the statement value.length.
Your call activates String.valueOf(char value[]) that throws NPE in case of null argument. String.valueOf(Object value) works only if you drop the object to this method. Have a look at here