Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a Null String into Integer

Tags:

java

casting

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.

like image 309
ARAZA Avatar asked Mar 07 '12 04:03

ARAZA


People also ask

Can NULL be cast to int?

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.

Can you cast a string into an integer?

In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.

Can we convert empty string to int in Java?

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.


2 Answers

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;
}
like image 152
Juvanis Avatar answered Sep 25 '22 05:09

Juvanis


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.

like image 40
Xavier Portebois Avatar answered Sep 23 '22 05:09

Xavier Portebois