Is there any way to cast a null to Integer. The null is actually a String, which i am passing in my service layer that accepts it as an Integer. So, whenever i try to cast a null String to Integer, it throws me an exception. But i have to cast the null into Integer.
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.
What if we passed a data type other than an int in parseInt() or valueOf()? The program will throw a NumberFormatException upon passing values other than numerics. An empty or null string is also liable for the same error and would not convert a string to an integer in java.
You cannot cast from String to Integer. However, if you are trying to convert string into integer and if you have to provide an implementation for handling null
Strings, take a look at this code snippet:
String str = "...";
// suppose str becomes null after some operation(s).
int number = 0;
try
{
if(str != null)
number = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
number = 0;
}
If you're using apache commons, there is an helper method that does the trick:
NumberUtils.createInteger(myString)
As said in the documentation:
"convert a String
to a Integer
, handling hex and octal notations; returns null
if the string is null
; throws NumberFormatException
if the value cannot be converted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With