Cast a Null String into Integer

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.


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

Try this


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

Tags:

Java

Casting