ARAZA
ARAZA

Reputation: 225

Cast a Null String into Integer

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.

Upvotes: 20

Views: 113709

Answers (6)

Nav
Nav

Reputation: 21

Try below code:application will return 0 if the string is null else it will parse the string to int if string contains a number alone..

Code:

(str.equals("null")?0:Integer.parseInt(str))

Upvotes: 2

Xavier Portebois
Xavier Portebois

Reputation: 3504

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.

Upvotes: 24

Juvanis
Juvanis

Reputation: 25950

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;
}

Upvotes: 26

Ullas Prabhakar
Ullas Prabhakar

Reputation: 3640

String s= "";  
int i=0;
i=Integer.parseInt(s+0);
System.out.println(i);

Try this

Upvotes: 9

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8540

If you are sure you only have to handle nulls,

int i=0;
i=(str==null?i:Integer.parseInt(str));
System.out.println(i);

for non integer strings it will throw Numberformat exception

Upvotes: 0

gtiwari333
gtiwari333

Reputation: 25156

What about this ?

private static void castTest() {
    System.out.println(getInteger(null));
    System.out.println(getInteger("003"));
    int a = getInteger("55");
    System.out.println(a);
}

private static Integer getInteger(String str) {
    if (str == null) {
        return new Integer(0);
    } else {
        return Integer.parseInt(str);
    }
}

Upvotes: 2

Related Questions